0% found this document useful (0 votes)
27 views30 pages

Adbms Modl3

Uploaded by

Nihana sherin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views30 pages

Adbms Modl3

Uploaded by

Nihana sherin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

1

UNIT 3

Relational Database Query Languages:-


It is the language by which user communicates with the DB. Relational query languages use relational
algebra to break the user requests and instruct the DBMS to execute the requests. It is the language
by which user communicates with the database. These relational query languages can be
procedural or non-procedural.

Procedural Query Language


A procedural query language will have set of queries instructing the DBMS to perform various
transactions in the sequence to meet the user request.

For example, get_CGPA procedure will have various queries to get the marks of student in each subject,
calculate the total marks, and then decide the CGPA based on his total marks.
This procedural query language tells the database what is required from the database and how to
get them from the database. Relational algebra is a procedural query language.
Non-Procedural Query Language
Non-procedural queries will have single query on one or more tables to get result from the database.
For example, get the name and address of the student with particular ID will have single query on
STUDENT table. Relational Calculus is a non procedural language which informs what to do with the
tables, but doesn’t inform how to accomplish this.

These query languages basically will have queries on tables in the database. In the relational
database, a table is known as relation. Records / rows of the table are referred as tuples. Columns
of the table are also known as attributes. All these names are used interchangeably in relational
database.

QBE AND SQL:-


Query by Example (QBE) :-
Query by example is a query language used in relational databases to allow the users to search
for information stored in tables and fields. This method provides a simple user interface where the
user will input an example of the data that people want to access.

The issue with normal queries like SQL Queries that users use to manage data in the database is
that they should be correct and should have a well-defined structure meaning they should follow the
proper syntax. Using an incorrect syntax or query, the user receives an error message, and the
application or measurement is terminated. Hence, to overcome the above-described problem,
“Query by Example” was introduced. It is a graphical query language in which users are given a
user interface and then asked to fill in the appropriate fields to obtain their desired result.

An error will be received if the query is incorrect in SQL; but, if the query is incorrect in QBE, will
either receive a wrong answer or the query will not be executed; in either case, the user will never
receive an error. One of the benefits of QBE is that users do not have to write full queries as they
would in SQL or other database languages; instead, QBE comes with certain blank spaces that fill
in to get the desired answer.
2

SQL (Structured Query Language) is used to perform operations on the records stored in
the database, such as updating records, inserting records, deleting records, creating and modifying
database tables, views, etc.

SQL is not a database system, but it is a query language.

This database language is mainly designed for maintaining the data in relational database
management systems. It is a special tool used by data professionals for handling structured data
(data which is stored in the form of tables). It is also designed for stream processing in RDSMS.

You can easily create and manipulate the database, access and modify the table rows and columns,
etc.

These SQL commands are mainly categorized into 4 categories as:


1. DDL – Data Definition Language
2. DML – Data Manipulation Language
3. DCL – Data Control Language
4.TCL – Transaction Control Language

DDL (Data Definition Language):


DDL or Data Definition Language actually consists of the SQL commands that can be used to
define the database schema. It simply deals with descriptions of the database schema and is used
to create and modify the structure of database objects in the database. DDL is a set of SQL
commands used to create, modify, and delete database structures but not data. These commands
are normally not used by a general user, who should be accessing the database via an application.
List of DDL commands:
• CREATE: This command is used to create the database or its objects (like table,
index, function, views, store procedure, and triggers).
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);

• DROP: This command is used to delete objects from the database.


Syntax
DROP TABLE table_name;
Example
DROP TABLE EMPLOYEE;

• ALTER: This is used to alter the structure of the database.


Syntax:
To add a new column in the table
ALTER TABLE table_name ADD column_name COLUMN-definition;
To modify existing column in the table:
ALTER TABLE table_name MODIFY(column_definitions....);

EXAMPLE

ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));


ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));
3

• TRUNCATE: This is used to remove all records from a table, including all spaces
allocated for the records are removed.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;

• COMMENT: This is used to add comments to the data dictionary.


• RENAME: This is used to rename an object existing in the database.

DML(Data Manipulation Language):


The SQL commands that deals with the manipulation of data present in the
database belong to DML or Data Manipulation Language and this includes most of the SQL
statements. It is the component of the SQL statement that controls access to data and to
the database. Basically, DCL statements are grouped with DML statements.

Here are some commands that come under DML:

• INSERT , UPDATE , DELETE

a.INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.

Syntax:
INSERT INTO TABLE_NAME
(col1, col2, col3,.... col N)
VALUES (value1, value2, value3, .... valueN);

Or

INSERT INTO TABLE_NAME


VALUES (value1, value2, value3, .... valueN);
For example:
INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITIO
N]
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.

Syntax:
DELETE FROM table_name [WHERE condition];
For example:
4

DELETE FROM javatpoint


WHERE Author="Sonoo";
DCL (Data Control Language):
DCL includes commands such as GRANT and REVOKE which mainly deal with the
rights, permissions, and other controls of the database system.
List of DCL commands:
• GRANT: This command gives users access privileges to the database.
• REVOKE: This command withdraws the user’s access privileges given by using
the GRANT command.
TCL (Transaction Control Language):
Transactions group a set of tasks into a single execution unit. Each transaction begins
with a specific task and ends when all the tasks in the group successfully complete. If any
of the tasks fail, the transaction fails. Therefore, a transaction has only two results: success
or failure,the following TCL commands are used to control the execution of a transaction:
• COMMIT: Commits a Transaction.
• ROLLBACK: Rollbacks a transaction in case of any error occurs.
• SAVEPOINT: Sets a save point within a transaction.
• SET TRANSACTION: Specifies characteristics for the transaction.

The SQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a database.

Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

The following example creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:

Example
CREATE TABLE Persons (
PersonID int NOT NULL,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
DESC (description) command used to check if our table is created or not.

DROP
DROP is used to delete a whole database or just a table.The DROP statement destroys
the objects like an existing database, table, index, or view.
A DROP statement in SQL removes a component from a relational database
5

management system (RDBMS).


Syntax:

DROP TABLE table_name;

table_name:- Name of the table to be deleted.


TRUNCATE
TRUNCATE statement is a Data Definition Language (DDL) operation that is used to
mark the extents of a table for deallocation (empty for reuse). The result of this operation
quickly removes all data from a table, typically bypassing a number of integrity enforcing
mechanisms.
Synax:-
TRUNCATE TABLE table_name;

table_name: Name of the table to be truncated.

DROP vs TRUNCATE
• Truncate is normally ultra-fast and its ideal for deleting data from a temporary
table.
• Truncate preserves the structure of the table for future use, unlike drop table
where the table is deleted with its full structure.
• Table or Database deletion using DROP statement cannot be rolled back, so it
must be used wisely.

The SQL SELECT Statement


The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

Syntax
SELECT column1, column2, ...
FROM table_name;

Here, column1, column2, ... are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use the following syntax:

SELECT * FROM table_name;

Example
SELECT CustomerName, City FROM Customers;

SQL - WHERE Clause


The SQL WHERE clause is used to specify a condition while fetching the data from a single table
or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific
6

value from the table. You should use the WHERE clause to filter the records and fetching only the
necessary records.
The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE,
DELETE statement, etc., which we would examine in the subsequent chapters.

Syntax
SELECT column1, column2, ...FROM table_name WHERE condition;

Example
SELECT * FROM Customers
WHERE Country='Mexico';

The SQL DELETE Statement

The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;

ote: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you
omit the WHERE clause, all records in the table will be deleted!

Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

SQL - ALTER TABLE Command

• The ALTER TABLE statement in Structured Query Language allows you to add, modify, and
delete columns of an existing table. This statement also allows database users to add and
remove various SQL constraints on the existing tables.
• Any user can also change the name of the table using this statement.
• Instead of creating a whole table or database again you can easily add single and multiple columns
using the ADD keyword.

ALTER TABLE table_name ADD column_name column-definition;

The above syntax only allows you to add a single column to the existing table. If you want to add
more than one column to the table in a single SQL statement, then use the following syntax:

ALTER TABLE table_name ADD (column_Name1 column-definition,


column_Name2 column-definition,
.....
column_NameN column-definition);
In many situations, you may require to delete the columns from the existing table. Instead of deleting the
whole table or database you can use DROP keyword for deleting the columns.
ALTER TABLE table_name DROP Column column_name ;
7

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only
want to list the different (distinct) values.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...
FROM table_name;

The following SQL statement selects only the DISTINCT values from the "Country"
column in the "Customers" table:

Example
SELECT DISTINCT Country FROM Customers;

The following SQL statement selects all (including the duplicates) values from the
"Country" column in the "Customers" table:

Example
SELECT Country FROM Customers;

SQL ALL Keyword;-


The ALL command returns true if all of the subquery values meet the condition.

The following SQL statement returns TRUE and lists the productnames if ALL the records
in the OrderDetails table has quantity = 10:

Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);

Selecting multiple columns with conditions;-


When we have to select multiple columns along with some condition, we put a WHERE
clause and write our condition inside that clause.

SYNTAX:
SELECT A1,A2,……An FROM R1,R2,….Rm WHERE P ;
(A- Attributes R- Relations P- conditions)
EXAMPLE;
• Selecting columns first name and last name i.e. SELECT First_Name,
Last_Name.
• From the employee table i.e. FROM Employee
there are two conditions,
• Salary must be 10000 i.e. Salary=10000
8

• the Last name should be Chauhan i.e. Last_name=’chauhan’

SELECT FirstName, LastName


FROM Employee
WHERE Salary=10000 OR LastName='Chauhan';
Natural join is an SQL join operation that creates join on the base of the common
columns in the tables. To perform natural join there must be one common
attribute(Column) between two tables. Natural join will retrieve from multiple relations.
SYNTAX;
SELECT [column_names | *] FROM table_name1 NATURAL JOIN table_name2;
EXAMPLS;
1. SELECT * FROM COUNTRIES NATURAL JOIN CITIES
2. SELECT NAME,COSTM_ID FROM instructor NATURAL JOIN teachers

Rename Operation ;
It is used to assign a new name to a relation and is denoted by ρ (rho).

Syntax
ρnewname (tablename or expression)
oldname AS newname
Example;
SELECT name AS in_name FROM instructor;
SQL String Operators
The string operators in SQL are used to perform important operations such as pattern
matching, concatenation, etc. where pattern matching is performed by using the
wildcard characters such as ‘%’ and ‘_’ in concurrence with the Like operator to search
for the specific patterns in strings and by the usage of concatenation operation one or
more strings or columns of the tables can be combined together.
Like Operator
This operator is used to decide if the specific character string matches the specific
pattern where the pattern can be a regular or wildcard character. While pattern
matching, the regular characters should match exactly with the specific characters of
the string but when we want to match the arbitrary fragments of the string, wildcard
characters can be used.
SELECT * FROM STUDENTS WHERE FIRSTNAME LIKE 'p%';
In the above query, the FIRSTNAME column is compared with the pattern ‘p%’ and
then it finds the Student name which starts with ‘p’
the wildcard character % is used before ‘j’ and this will find the values which end with
‘j’.
SELECT * FROM STUDENTS WHERE FIRSTNAME LIKE '%j';
9

In the below query, any value which starts and ends with a specific character can be
found.
SELECT FIRSTNAME FROM STUDENTS WHERE FIRSTNAME LIKE 'p%y';

In the below query, the values which matches the pattern in any position is found.
SELECT * FROM STUDENTS WHERE FIRSTNAME LIKE '%a%';

The ‘%a%’ finds any value which has ‘a’ in any position of the first name .

The other wildcard character ‘_’ is used to match any single character. If we want to
find any character at a particular position, we can do so by using the character ‘_’ as
shown in the below query.
SELECT FIRSTNAME FROM STUDENTS WHERE FIRSTNAME LIKE '_a%';
The above query will display the FIRSTNAME of the students ‘Raj’ and ‘Harry’ as they
have ‘a’ at the second position in their first names.

Also, we can see that in the below query, the values of the FIRSTNAME which start
with ‘p’ having the character length of at least 2 can be found.
SELECT FIRSTNAME FROM STUDENTS WHERE FIRSTNAME LIKE 'p_%';
In a result, it can be seen that the first name ‘Preeti’ starts with ‘p’ and has a length of
at least two characters.

The SQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

The following SQL statement selects all customers from the "Customers" table, sorted by
the "Country" column:

Example
SELECT * FROM Customers
ORDER BY Country;

The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
10

Example
SELECT * FROM Customers
ORDER BY Country DESC;

The SQL BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.

The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

The following SQL statement selects all products with a price between 10 and 20:

Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

UNION / EXCEPT / INTERSECT


UNION, EXCEPT, and INTERSECT are operators that operate similarly and are used between two queries to
form Boolean combinations between the results of the two queries. Given queries A and B, UNION returns
all records returned by either A or B. EXCEPT returns all records in A but not in B. INTERSECT returns all
records returned by both A and also by B. Tables returned by UNION, EXCEPT and INTERSECT by default
will have duplicate records eliminated. Use ALL to retain duplicates in the results table.

Syntax UNION
{ <query_specification> | ( <query_expression> ) }
{ UNION | UNION ALL}
{ <query_specification> | ( <query_expression> ) }
Example-1
You want to invite all the Speakers and Authors for the annual conference.
1. select name from Speakers
2. union
3. select name from Authors
4. order by name
INTERSECT
It is used to take the result of two queries and returns the only those rows which are common in both
result sets. It removes duplicate records from the final result set.Syntax;-

{ <query_specification> | ( <query_expression> ) }

{ EXCEPT | INTERSECT }

{ <query_specification> | ( <query_expression> ) }
11

Example-3

You want the list of people who are Speakers and they are also Authors.

1. select name from Speakers


2. intersect
3. select name from Authors
4. order by name
EXCEPT
It is used to take the distinct records of two one query and returns the only those rows which do not
appear in the second result set.Syntax;-

{ <query_specification> | ( <query_expression> ) }

{ EXCEPT | INTERSECT }

{ <query_specification> | ( <query_expression> ) }

Example-4 You want the list of people who are only Speakers and they are not Authors.

1. select name from Speakers


2. except
3. select name from Authors
4. order by name
Aggregate functions in SQL
In database management an aggregate function is a function where the values of multiple
rows are grouped together as input on certain criteria to form a single value of more
significant meaning.
Various Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
EXAMPLES;

SELECT Avg(salary) FROM instr;


SELECT Count(ID) FROM teachers;
SELECT count(*) FROM teachers;
SELECT Sum(salary) FROM teachers;

The SQL HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.HAVING Syntax;
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
12

The following SQL statement lists the number of customers in each country. Only include
countries with more than 5 customers:

Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

SQL IN Operator
o IN is an operator in SQL, which is generally used with a WHERE clause.
o Using the IN operator, multiple values can be specified.
o It allows us to easily test if an expression matches any value in a list of values.
o IN operator is used to replace many OR conditions.

Syntax of IN operator in SQL:


SELECT ColumnName FROM TableName WHERE ColumnName IN (Value 1, Value2….Value n)
EXAMPLE;
SELECT *FROM t_students WHERE Hometown IN ("Faridabad", "Panipat”,”Jaipur”);

The SQL UPDATE Statement


The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

Note: Be careful when updating records in a table! Notice the WHERE clause in
the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If
you omit the WHERE clause, all records in the table will be updated!

The following SQL statement updates the first customer (CustomerID = 1) with a new
contact person and a new city.

Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

SQL CONSTRAINTS (Constraint Clause)


SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the table. If there is any violation between the constraint and the data action,
the action is aborted.Constraints can be column level or table level. Column level constraints apply to
a column, and table level constraints apply to the whole table.
✓ Constraints are the rules enforced on data columns on a table. These are used to limit the type
of data that can go into a table. This ensures the accuracy and reliability of the data in the
database.
13

✓ Constraints can either be column level or table level. Column level constraints are applied only
to one column whereas, table level constraints are applied to the entire table.
Following are some of the most commonly used constraints available in SQL − NOT
NULL Constraint − Ensures that a column cannot have a NULL value.
• DEFAULT Constraint − Provides a default value for a column when none is specified.
• UNIQUE Constraint − Ensures that all the values in a column are different.
• PRIMARY Key − Uniquely identifies each row/record in a database table.
• FOREIGN Key − Uniquely identifies a row/record in any another database table.
• CHECK Constraint − The CHECK constraint ensures that all values in a column satisfy certain
conditions.
• INDEX − Used to create and retrieve data from the database very quickly.

SQL NOT NULL Constraint


By default, a column can hold NULL values.The NOT NULL constraint enforces a column to NOT accept
NULL values.This enforces a field to always contain a value, which means that you cannot insert a new
record, or update a record without adding a value to this field.
Sql Not Null On Create Table
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept NULL
values when the "Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

SQL UNIQUE Constraint


The UNIQUE constraint ensures that all values in a column are different.Both the UNIQUE and PRIMARY
KEY constraints provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.However, you can have many
UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
Sql Unique Constraint On Create Table
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is created:
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);

SQL PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a table.Primary keys must contain
UNIQUE values, and cannot contain NULL values.A table can have only one primary key, which may
consist of single or multiple fields.
Sql Primary Key On Create Table
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:
My SQL
CREATE TABLE Persons (
14

ID int NOT NULL,


LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

SQL FOREIGN KEY Constraint


A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY is a field (or collection of fields)
in one table that refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing the candidate
key is called the referenced or parent table.
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is
created:
MySQL:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.If you define a
CHECK constraint on a single column it allows only certain values for this column.If you define a CHECK
constraint on a table it can limit the values in certain columns based on values in other columns in the
row. Sql Check On Create Table
The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created.
The CHECK constraint ensures that you can not have any person below 18 years:
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

SQL DEFAULT Constraint


The DEFAULT constraint is used to provide a default value for a column.The default value will be added
to all new records IF no other value is specified.
Sql Default On Create Table
The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created:
My SQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
15

SQL Logical Operators

Here is a list of all the logical operators available in SQL.


Sr.No. Operator & Description

ALL
1
The ALL operator is used to compare a value to all values in another value set.

AND
2 The AND operator allows the existence of multiple conditions in an SQL
statement's WHERE clause.

ANY
3 The ANY operator is used to compare a value to any applicable value in the list as
per the condition.

BETWEEN
4 The BETWEEN operator is used to search for values that are within a set of values,
given the minimum value and the maximum value.

EXISTS
5 The EXISTS operator is used to search for the presence of a row in a specified table
that meets a certain criterion.

IN
6 The IN operator is used to compare a value to a list of literal values that have
been specified.

7 LIKE

The LIKE operator is used to compare a value to similar values using wildcard
operators.

NOT
The NOT operator reverses the meaning of the logical operator with which it is
8 used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.

OR
9 The OR operator is used to combine multiple conditions in an SQL statement's
WHERE clause.

IS NULL
10 The NULL operator is used to compare a value with a NULL value.

UNIQUE
11 The UNIQUE operator searches every row of a specified table for uniqueness (no
duplicates).
16

SQL Data Types


Data types are used to represent the nature of the data that can be stored in the database table. For example,
in a particular column of a table, if we want to store a string type of data then we will have to declare a string
data type of this column.

Data types mainly classified into three categories for every database.

• String Data types


• Numeric Data types
• Date and time Data types
MySQL Data Types

A list of data types used in MySQL database. This is based on MySQL 8.0.

MySQL String Data Types


17
18

Variable Types in SQL: Local, Global


MS SQL has two types of variables:
1. Local variable
2. Global variable.
However, the user can only create a local variable. Local
variable:
• A user declares the local variable.
• By default, a local variable starts with @.
• Every local variable scope has the restriction to the current batch or procedure within any given
session.
Global variable:
• The system maintains the global variable. A user cannot declare them. ● The global
variable starts with @@
• It stores session related information.

How to DECLARE a variable in SQL


• Before using any variable in batch or procedure, you need to declare the variable.
• DECLARE command is used to DECLARE variable which acts as a placeholder for the memory
location.
• Only once the declaration is made, a variable can be used in the subsequent part of batch or
procedure.
TSQL Syntax:
DECLARE { @LOCAL_VARIABLE[AS] data_type [ = value ] }
Rules:
• Initialization is an optional thing while declaring.
• By default, DECLARE initializes variable to NULL.
• Using the keyword ‘AS’ is optional.
• To declare more than one local variable, use a comma after the first local variable definition, and
then define the next local variable name and data type.
Examples of Declaring a variable:
Query: With ‘AS’
DECLARE @COURSE_ID AS INT;

Query: Without ‘AS’


DECLARE @COURSE_NAME VARCHAR (10);

Query: DECLARE two variables


DECLARE @COURSE_ID AS INT, @COURSE_NAME VARCHAR (10);

Assigning a value to SQL Variable


You can assign a value to a variable in the following three ways:
1. During variable declaration using DECLARE keyword.
2. Using SET
3. Using SELECT

During variable declaration using DECLARE keyword


T-SQL Syntax:
DECLARE { @Local_Variable [AS] Datatype [ = value ] }

Here, after datatype we can use ‘=’ followed by value to be assigned Query:
DECLARE @COURSE_ID AS INT = 5 PRINT @COURSE_ID
19

Using SQL SET VARIABLE


Sometimes we want to keep declaration and initialization separate. SET can be used to assign values to
the variable, post declaring a variable.Below are the different ways to assign values using SET:
Example: Assigning a value to a variable using SET Syntax:
DECLARE @Local_Variable <Data_Type>

SET @Local_Variable = <Value>


Query:
DECLARE @COURSE_ID AS INT

SET @COURSE_ID = 5

PRINT @COURSE_ID

Using SQL SELECT VARIABLE


Just like SET, we can also use SELECT to assign values to the variables, post declaring a variable using
DECLARE. Below are different ways to assign a value using SELECT:
Example: Assigning a value to a variable using SELECT Syntax:
DECLARE @LOCAL_VARIABLE <Data_Type>

SELECT @LOCAL_VARIABLE = <Value> Query:


DECLARE @COURSE_ID INT

SELECT @COURSE_ID = 5

PRINT @COURSE_ID
Example: Assigning a value to multiple variable using SELECT Syntax:
DECLARE @Local_Variable _1 <Data_Type>, @Local_Variable _2
<Data_Type>,SELECT @Local_Variable _1 = <Value_1>, @Local_Variable _2 =
<Value_2>
Rules: Unlike SET, SELECT can be used to assign a value to multiple variables separated by the
comma.
DECLARE @COURSE_ID as INT, @COURSE_NAME AS VARCHAR(5) SELECT
@COURSE_ID = 5, @COURSE_NAME = 'UNIX'
PRINT @COURSE_ID

PRINT @COURSE_NAME

Range Search and Pattern Matching


The BETWEEN operator is used in the WHERE clause to select a value within a range of values. We often use the
BETWEEN operator in the WHERE clause of the SELECT, UPDATE and DELETEstatements.

The following illustrates how to use the BETWEEN operator:


SELECT column_1, column_2 FROM table WHERE (expr | column) BETWEEN lower_value AND upper_value;
example
The following query selects product whose unit price is from $18 to $19
SELECT productName, unitPrice
FROM products WHERE unitPrice BETWEEN 18 AND 19;

SELECT lastname, firstname, birthdate FROM employees WHERE birthdate BETWEEN '1948-01-01' AND '1960-01-
01';

SELECT productName, unitPrice


FROMProducts WHERE unitPrice NOT BETWEEN 18 AND 19;
20

Pattern Matching in SQL


• LIKE clause is used to perform the pattern matching task in SQL.
• A WHERE clause is generally preceded by a LIKE clause in an SQL query.
• LIKE clause searches for a match between the patterns in a query with the pattern in the values present in
an SQL table. If the match is successful, then that particular value will be retrieved from the SQL table.
• LIKE clause can work with strings and numbers.

The LIKE clause uses the following symbols known as wildcard operators in SQL to perform this pattern-matching task
in SQL.

1. To represent zero, one or more than one character, % (percentage) is used.


2. To represent a single character _ (underscore) is used.

Let us start with the syntax of a LIKE clause:

SELECT ColumnName1, ColumnName2 FROM TableName WHERE ColumnName LIKE [Expression]

Here, Expression refers to the pattern which we want to search for in the values of a table. This expression will include
the wildcard operators such as '%' and '_'.

(A) Using LIKE clause with % (percentage)

Example 1: Write a query to display employee details in which name starts with 'Pr'.

Query:

1. mysql> SELECT * FROM employee_details WHERE Name LIKE 'Pr%';

We have used the SELECT query with the WHERE clause applied on the Name column followed by the LIKE clause. We
have specified the expression value as 'Pr' in the LIKE clause, followed by the wildcard operator percent (%). So,
according to the query, all the records that have names starting with the string 'Pr' followed by any other character
will be considered a part of the output.

1. mysql> SELECT * FROM employee_details WHERE Name LIKE '%ya%'; all the
records which have names containing 'ya' as the substring Write a query to display
employee details in which city name ends with 'i'.
Query:

1. mysql> SELECT * FROM employee_details WHERE City LIKE '%i';

Write a query to display employee details in which age number starts with 2.

Query:

1. mysql> SELECT * FROM employee_details WHERE Age LIKE '2%';

(B) Using LIKE clause with _ (underscore)

Example 1:

Write a query to display employee details in which city name starts with 'Na', ends with 'ik', and contains any single
character between 'Na' and 'ik'.

Query:

1. mysql> SELECT * FROM employee_details WHERE City LIKE 'Na_ik';


21

Example 2:

Write a query to display employee details in which salary contains a number starting with '3' succeeding any two
digits and finally ends with '00'.

Query:

1. mysql> SELECT * FROM employee_details WHERE Salary LIKE '3__00';

(C) Using LIKE clause with % and _ operator in a single query

Example 1: Write a query to display employee details in which employee name contains
'a' at fifth position.

Query:

1. mysql> SELECT * FROM employee_details WHERE Name LIKE '____a%';

(D) Using LIKE clause with NOT operator

Example 1:

Write a query to display employee details in which employee name is not like 'Priya'.

Query:

mysql> SELECT * FROM employee_details WHERE Name NOT LIKE 'Priya%';

SQL JOIN
In SQL, JOIN clause is used to combine the records from two or more tables in a database.
Types of SQL JOIN
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
23

1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long as the condition is
satisfied. It returns the combination of all rows from both the tables where the condition satisfies.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME,
PROJECT.DEPARTMENT
FROM EMPLOYEE
INNER JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from the right table. If there is no matching join value,
it will return NULL. Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
LEFT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right table and the matched values from the left table. If
there is no matching in both tables, it will return NULL.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
RIGHT JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;

4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join tables have all the records from both tables. It puts
NULL on the place of matches not found.
Syntax
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Query
SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
FROM EMPLOYEE
FULL JOIN PROJECT
ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
24

SQL VIEWS
Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a real table in
the database. We can create a view by selecting fields from one or more tables present in the
database. A View can either have all the rows of a table or specific rows based on certain condition.
In this article we will learn about creating , deleting and updating Views.
Sample Tables:
StudentDetails

StudentMarks

CREATING VIEWS

We can create View using CREATE VIEW statement. A View can be created from a single table or
multiple tables. Syntax:

CREATE VIEW view_name AS SELECT column1, column2.....


FROM table_name
WHERE condition;

Name for the View

Examples:
Creating View from a single table:
In this example we will create a View named DetailsView from the table StudentDetails. Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM DetailsView;
In this example, we will create a view named StudentNames from the
table StudentDetails.
25

Query:
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;
If we now query the view as,
SELECT * FROM StudentNames; Output:

Creating View from multiple tables:

In this example we will create a View named MarksView from two tables StudentDetails and
StudentMarks. To create a View from multiple tables we can simply include multiple tables in the
SELECT statement. Query:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;
To display data of View MarksView:
SELECT * FROM MarksView; Output:

DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed any more? Obviously
we will want to delete it. SQL allows us to delete an existing View. We can delete or drop a View using
the DROP statement.
26

UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of these conditions is
not met, then we will not be allowed to update the view.
1. The SELECT statement which is used to create the view should not include GROUP BY clause or
ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using multiple tables then
we will not be allowed to update the view.
We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view.
Syntax:

CREATE OR REPLACE VIEW view_name AS SELECT column1,coulmn2,..


FROM table_name
WHERE condition;
For example, if we want to update the view MarksView and add the field AGE to this View from
StudentMarks Table, we can do this as: CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,
StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME; If we
fetch all the data from MarksView now as:
SELECT * FROM MarksView;
Output:

USING VIEW WITH CHECK OPTION

The WITH CHECK OPTION clause in SQL is a very useful clause for views. It is applicable to a updatable
view. If the view is not updatable, then there is no meaning of including this clause in the CREATE
VIEW statement.
• The WITH CHECK OPTION clause is used to prevent the insertion of rows in the view where the
condition in the WHERE clause in CREATE VIEW statement is not satisfied.
• If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and if the UPDATE
or INSERT clause does not satisfy the conditions then they will return an error. Example:
In the below example we are creating a View SampleView from StudentDetails Table with WITH CHECK
OPTION clause.
CREATE VIEW SampleView AS
SELECT S_ID, NAME
FROM StudentDetails WHERE NAME IS NOT NULL WITH CHECK OPTION;
In this View if we now try to insert a new row with null value in the NAME column then it will give an
error because the view is created with the condition for NAME column as NOT NULL.
For example,though the View is updatable but then also the below query for this View is not valid:
INSERT INTO SampleView(S_ID) VALUES(6);
27

Triggers
• A trigger is a stored procedure in database which automatically invokes whenever a special event in the
database occurs.
• For example: a trigger can be invoked when row is inserted into a specified table or when certain table
columns are being updated.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete} on [table_name]
[for each row]
[trigger_body]
Explanation of syntax:
1. create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name.
2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. on [table_name]: This specifies the name of the table associated with the trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row being
affected.
6. [trigger_body]: This provides the operation to be performed as trigger is fired.

Creating a Trigger
CREATE TRIGGER sample_trigger
Before insert
On student
For each row
Set new.total=new.mark/6;

Here new keyword is used to refer the


row that is getting affected.
28

PL/SQL After Update Trigger Syntax


Syntax
CREATE [OR REPLACE ] TRIGGER trigger_name
AFTER UPDATE ON table_name
[FOR EACH ROW]
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

PL/SQL After Delete Trigger Syntax


Syntax
CREATE [OR REPLACE ] TRIGGER trigger_name
AFTER DELETE ON table_name
[FOR EACH ROW]
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Lock-based Protocols
Lock Based Protocols in DBMS is a mechanism in which a transaction cannot Read or Write
the data until it acquires an appropriate lock. Lock based protocols help to eliminate the
concurrency problem in DBMS for simultaneous transactions by locking or isolating a
particular transaction to a single user.
A lock is a data variable which is associated with a data item. This lock signifies that
operations that can be performed on the data item. Locks in DBMS help synchronize
access to the database items by concurrent transactions. All lock requests are made to
the concurrency-control manager. Transactions proceed only once the lock request is
granted.

There are two types of lock:


29

1. Shared Lock (S):


A shared lock is also called a Read-only lock. With the shared lock, the data item
can be shared between transactions. This is because you will never have
permission to update data on the data item. For example, consider a case where
two transactions are reading the account balance of a person. The database will let
them read by placing a shared lock. However, if another transaction wants to
update that accountʼs balance, shared lock prevent it until the reading process is
over.
2. Exclusive Lock (X):
With the Exclusive Lock, a data item can be read as well as written. This is exclusive
and canʼt be held concurrently on the same data item. X-lock is requested using
lock-x instruction. Transactions may unlock the data item after finishing the ʻwriteʼ
operation.
For example, when a transaction needs to update the account balance of a person.
You can allows this transaction by placing X lock on it. Therefore, when the second
transaction wants to read or write, exclusive lock prevent this operation.

Lock Compatibility Matrix –

The
figure illustrates that when two transactions are involved, and both
attempt to only read a given data item, it is permitted and no conflict
arises, but when one transaction attempts to write the data item and
another one tries to read or write at the same time, conflict occurs
resulting in a denied interaction.
Starvation
Starvation is the situation when a transaction needs to wait for an indefinite
period to acquire a lock.
Following are the reasons for Starvation:
● When waiting scheme for locked items is not properly managed
● In the case of resource leak
● The same transaction is selected as a victim repeatedly
Deadlock
30

Deadlock refers to a specific situation where two or more processes are


waiting for each other to release a resource or more than two processes are
waiting for the resource in a circular chain.

Two Phase Locking Protocol


Two Phase Locking Protocol also known as 2PL protocol is a method of
concurrency control in DBMS that ensures serializability by applying a lock to
the transaction data which blocks other transactions to access the same data
simultaneously. Two Phase Locking protocol helps to eliminate the
concurrency problem in DBMS.
This locking protocol divides the execution phase of a transaction into three
different parts.
● In the first phase, when the transaction begins to execute, it requires
permission for the locks it needs.
● The second part is where the transaction obtains all the locks. When a
transaction releases its first lock, the third phase starts.
● In this third phase, the transaction cannot demand any new locks.
Instead, it only releases the acquired locks.

The Two-Phase Locking protocol allows each transaction to make a lock or unlock
request in two steps:
● Growing Phase: In this phase transaction may obtain locks but may not
release any locks.
● Shrinking Phase: In this phase, a transaction may release locks but not obtain
any new lock It is true that the 2PL protocol offers serializability. However, it
does not ensure that deadlocks do not happen.
31

Types of 2 Phase Locking (PL)


Here are the types of 2 phase locking mention below
1. Conservative 2PLConservative or Static 2PL when implied acquires all the locks before a
transaction begins and releases the locks once the transaction is committed. This kind of 2
PL helps in overcoming problems related to cascading rollback and deadlocks.
2. Strict 2PL
In this type of 2PL, the exclusive (write) lock is released only after a transaction is
committed, whereas a shared (read) lock can be released at regular intervals. Though Strict
2PL helps overcome the cascading rollback issues, it may also cause a bottleneck in some
cases.

3. Strong strict or Rigorous 2PL


In this type of 2PL, both shared and exclusive locks are released only when
the transaction is ended, i.e. when the transaction is committed or aborted.
This kind of 2PL is used in practice today, promotes serializability and is
simpler to implement due to the strictness involved w.r.t the implementation
of the phase endings.

This is just a skeleton transaction that shows how unlocking and locking work with 2-PL. Note for:
Transaction T1:
● The growing Phase is from steps 1-3.
● The shrinking Phase is from steps 5-7.
● Lock Point at 3
Transaction T2:
● The growing Phase is from steps 2-6.
● The shrinking Phase is from steps 8-9.
● Lock Point at 6

You might also like