Adbms Modl3
Adbms Modl3
UNIT 3
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.
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.
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.
EXAMPLE
• 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;
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
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'
Syntax:
DELETE FROM table_name [WHERE condition];
For example:
4
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
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.
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:
Example
SELECT CustomerName, City FROM Customers;
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';
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';
• 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.
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:
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.
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;
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);
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
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 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 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;
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.
{ <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.
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.
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;
✓ 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.
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
Data types mainly classified into three categories for every database.
A list of data types used in MySQL database. This is based on MySQL 8.0.
Here, after datatype we can use ‘=’ followed by value to be assigned Query:
DECLARE @COURSE_ID AS INT = 5 PRINT @COURSE_ID
19
SET @COURSE_ID = 5
PRINT @COURSE_ID
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
SELECT lastname, firstname, birthdate FROM employees WHERE birthdate BETWEEN '1948-01-01' AND '1960-01-
01';
The LIKE clause uses the following symbols known as wildcard operators in SQL to perform this pattern-matching task
in SQL.
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 '_'.
Example 1: Write a query to display employee details in which name starts with 'Pr'.
Query:
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:
Write a query to display employee details in which age number starts with 2.
Query:
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:
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:
Example 1: Write a query to display employee details in which employee name contains
'a' at fifth position.
Query:
Example 1:
Write a query to display employee details in which employee name is not like 'Priya'.
Query:
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:
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:
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:
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;
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.
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
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
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