Unit 3 Query Languages_3
Unit 3 Query Languages_3
Lecture no 1
Query Languages
Query Languages
• Relational Algebra
• SQL: DDL, DML, Select Queries, Set, String, Date and Numerical
Functions, Aggregate Functions ,Group by and Having Clause
• Join Queries, Nested queries
• DCL, TCL
• PL/SQL: Procedure, Function, Trigger
• Mapping of Relational Algebra to SQL
Relational Algebra
• The relational algebra provides basic operations which can be performed over
single or multiple relations in order to generate new relations(single or
multiple).
• Relational algebra is a procedural query language which follows a particular
syntax with the help of which, data can be accessed and retrieved very easily
from single as well as multiple table/data sources.
• Certain operators are used to perform queries and retrieve desired results.
• These operators can perform certain operations on single attribute(called
unary operator) or multiple attribute(called binary operator).
• Types of operations in relational algebra
• 1. Basic Operations
• 2. Derived Operations
Relational Algebra
• Basic/Fundamental Operations:
• 1. Select (σ)
• 2. Project (∏)
• 3. Union (∪)
• 4. Set Difference (-)
• 5. Cartesian product (X)
• 6. Rename (ρ)
• Derived Operations:
• 1. Natural Join (⋈)
• 2. Left, Right, Full outer join (⟕, ⟖, ⟗)
Relational Algebra : Operations
• Select (σ): This operation is used to fetch rows from given table or relation
on the basis of given conditions, it is denoted by “Sigma(σ)”.
• Syntax : σ Condition/Predicate(Relation/Table name)
• where clause in SQL, is used for the same purpose.
• For example : Consider the table of relation R(Roll No, Name, Age, Marks). If
we want to select the name and age of student, then it can be done by:
• Query Used : σ Name and Age>21 (Student_Details)
Relational Algebra : Operations
• Project(∏): This operation is also used to fetch all the rows/tuples/data
according to the requested attribute/Column. It means, using project
operation one can simply fetch all the tuples corresponding to a single
attribute or multiple attributes. It does not supports any conditions as select
operation and is denoted using “Pie(π)”.
• Syntax :∏column_name1,column_name2,..,column_nameN(table_name)
• Project operator in relational algebra is similar to the Select statement in SQL.
• For example : Consider the table of relation R(Roll No, Name, Age, Marks). If
we want to project the marks column, then it can be done by :
• Query Used : πMarks(Student_Details)
Relational Algebra : Operations
• Union(∪):In order to fetch data from two relations to generate new relation
with combined capabilities, union operations can be used. The union operation
fetches the data from both tables and projects it accordingly. It is denoted
through “Union Symbol(U)”.
• In Union Operation Both the relations compulsory to have same domain for
attributes.
• Syntax : X1 U X2 , where X1 & X2 are two different relations satisfying the
above two conditions.
• Note: The rows (tuples) that are present in both the tables will only appear once
in the union set. In short you can say that there are no duplicates present after
the union operation.
Relational Algebra : Operations
• Intersection(∩) : Intersection operator is denoted by ∩ symbol and it is used
to select common rows (tuples) from two tables (relations).
• Lets say we have two relations R1 and R2 both have same columns and we
want to select all those tuples(rows) that are present in both the relations,
then in that case we can apply intersection operation on these two relations
R1 ∩ R2.
• Note: Only those rows that are present in both the tables will appear in the
result set. COURSE ∩ STUDENT
Relational Algebra : Operations
• Set Difference (-) : In order to fetch the data which is not present in any one
of the relation, set difference operation is used. The set difference operation
is denoted by “Minus(-)”.
• Lets say we have two relations R1 and R2 and we want to select all those
tuples(rows) that are present in Relation R1 but not present in Relation R2,
this can be done using Set difference R1 – R2.
• For example : Consider the two tables with relations X1(Name, Age) and
X2(Name, Age). If we wish to apply the set difference operation, then it can
be done by :
Relational Algebra : Operations
• Cartesian product (X): The Cartesian product operation will generate the
possible combinations among the tuples from the relations resulting in
table containing all the data.
• It combines the information of two or more relations in one single relation.
Cartesian product is different from union operation and is denoted by
“Cross(X)”.
Relational Algebra : Operations
• Rename (ρ) : Rename (ρ) operation can be used to rename a relation or an
attribute of a relation.
• Rename (ρ) Syntax: ρ(new_relation_name, old_relation_name)
• Query: ρ(CUST_NAMES, ∏(Customer_Name)(CUSTOMER))
Relational Algebra
Relational Algebra
• Basic/Fundamental Operations:
• 1. Select (σ)
• 2. Project (∏)
• 3. Union (∪)
• 4. Set Difference (-)
• 5. Cartesian product (X)
• 6. Rename (ρ)
• Derived Operations:
• 1. Natural Join (⋈)
• 2. Left, Right, Full outer join (⟕, ⟖, ⟗)
Relational Algebra : Joins
• The database joins has the ability of
combining two or more data
tables/tuples into a single table/table
only if the following conditions are
satisfied.
• There must be a common attribute in
both(tables which are participating)
tables.
• Join condition must be satisfied.
• Database joins can be broadly
classified into two categories which
are further categorized into sub
categories.
Relational Algebra : Joins (The Inner Joins)
• When inner join is applied to tuples or tables, only those tuples of the table are kept
which have common attribute in all the tables. Other tuples which are not common are
dropped from the resulting tuple/table.
• Two possible inner joins are available i.e. Theta Join & Natural Join.
• Theta Join :If a condition is satisfied by the participating tables from different relations, then
the tuples are combined together using Theta Join. Theta join is denoted through
“Theta(Θ)”.
• Syntax : R1(X1, X2,X3…Xn) ⋈(Condition “θ”) R2(Y1, Y2,Y3…Yn) where, R1 and R2 are
relations having (X1, X2,X3…Xn) and (Y1, Y2,Y3…Yn) as attributes respectively.
• For example : Consider the
tables Student_Details and
Student_Result. Now, if we
want to implement theta join
on these relations, the result
will look like:
Relational Algebra : Joins (The Inner Joins)
• Natural Join (⋈):
• Natural join does not supports any condition such as theta join and works
only if, one attribute or more than one attributes are common between the
joining/participating relations.
• Syntax : R1(X1, X2,X3…Xn) ⋈ R2(Y1, Y2,Y3…Yn) where, R1 and R2 are
relations having (X1, X2,X3…Xn) and (Y1, Y2,Y3…Yn) as attributes
respectively.
• For example : Consider the tables Student_Details and Student_Result. Now,
if we want to implement natural join on these relations, the result will be
Relational Algebra : Joins (The Outer Joins)
• Outer Join (⋈):Outer join overcomes the inability of inner joins of dropping the
tuples which are uncommon among participating relations. If we want to display
those tuples which are not common, the concept of outer join is used.
• Also, if all the tuples needs to be displayed from all the participating relations,
outer joins can be used. They are of three types : Left Outer Join, Right Outer Join
& Full Outer Join.
• Left Outer Join
• There exists a concept of position(left or right) of relations in case of both left and
right outer join.
• In the left outer join, operation allows keeping all tuple in the left relation.
• If in case any tuple in left relation does not matches with the tuple in right
relation, NULL value will be displayed against that tuple in the resulting relation.
Relational Algebra : Joins (The Outer Joins)
• Left Outer Join:
• SQL stands for Structured Query Language. It is used for storing and
managing data in relational database management system (RDMS).
• It is a standard language for Relational Database System. It enables a
user to create, read, update and delete relational databases and
tables.
• All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL
Server use SQL as their standard database language.
• SQL allows users to query the database in a number of ways, using
English-like statements.
SQL Datatype
• SQL Datatype is used to define the values that a column can contain.
• Every column is required to have a name and data type in the
database table.
Data type Description
char It has a maximum length of 8000 characters. It contains Fixed-length non-unicode characters.
varchar It has a maximum length of 8000 characters. It contains variable-length non-unicode characters.
text It has a maximum length of 2,147,483,647 characters. It contains variable-length non-unicode characters.
Datatype Description
timestamp It stores the year, month, day, hour, minute, and the second value.
SQL Datatype
Data type Description
• The RIGHT OUTER JOIN in MySQL retrieves all the matching rows from both
the tables as well as non-matching rows from the right-side table.
• In this case, the un-matching data will take a null value.
• we need to write a query to retrieve EmployeeId, Name, Department, City,
and Title as Project from the Employee and Projects tables.
• Here, we got all 11 rows (i.e. all the rows from the Projects Table). If you
further notice, here, we got all the matching records from both the tables
Employee and Projects as well as all the non-matching rows from the right-
side table i.e. the Projects Table.
Joins in SQL
• Full Outer Join in MySQL
• The FULL OUTER JOIN retrieves all the matching rows from both
the tables as well as non-matching rows from both the tables
involved in the Join. In this case, the un-matching data will take
a null value. MySQL doesn’t support FULL OUTER JOIN; we will
achieve the FULL OUTER JOIN using UNION Operator in MySQL
• Nested queries are those queries which have an outer query and inner subquery.
• So, basically, the subquery is a query which is nested within another query such as SELECT,
INSERT, UPDATE or DELETE.
• SQL subqueries or nested queries are SQL statements where we need
the results from our database after using multiple filters.
SELECT column_name
FROM table_name1
WHERE VALUE IN
(SELECT column_name
FROM table_name2
WHERE condition)
Nested queries in SQL
• Rules to Use Subqueries in SQL
• Subqueries need to be enclosed in the Where clause and can be used with
Insert, Update, Delete, and Select statements.
• We can use comparison operators for example: <, >, > =, < =, !=, IN , Between
for the subqueries.
• The subquery is always executed first and then the main query.
• Subquery should be enclosed within parentheses.
• Subqueries are always to the right of the comparison operators.
• We can’t use Order By clause in the subquery; instead, we can use the Group
By clause.
• We can’t use Between clause with a subquery, but we can use Between in a
subquery.
Nested queries in SQL • Update Statement with Subquery
• SELECT Statement with Subquery • Example 2: Let us increase the
• Example 1: Let us find the second salary of Senior Manager to 35000.
highest salary of the employee in UPDATE EMP AS E, (SELECT
emp EmployeeID FROM emp WHERE
SELECT emp_id, MAX(salary) AS post='Sr.Manager') AS P
salary SET E.salary=35000
FROM emp WHERE E.EmployeeID =
WHERE salary < (SELECT MAX(salary) P.EmployeeID;
FROM emp);
Data Control Language
• DCL commands are used to grant and take back authority from any database
user.
• Here are some commands that come under DCL:
• Grant
• Revoke
• Grant: It is used to give user access privileges to a database.
• Example GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
• Revoke: It is used to take back permissions from the user.
• Example REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
Transaction Control Language
• TCL commands can only use with DML commands like INSERT, DELETE and
UPDATE only.
• Here are some commands that come under TCL:
• COMMIT
• ROLLBACK
• SAVEPOINT
• Commit: Commit command is used to save all the transactions to the
database.
• Syntax: COMMIT;
DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
Transaction Control Language
• ROLLBACK TO SavePoint2;
• Once you execute the above
rollback statement, then
commit the transaction by
executing the below commit
statement which will
commit two records
(ProductId 1005 and 1006)
into the database.
• COMMIT;
Transaction Control Language
• Rollback: Rollback command is used to undo transactions that have
not already been saved to the database.
• Syntax: ROLLBACK;
DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
• SAVEPOINT: It is used to roll the transaction back to a certain point
without rolling back the entire transaction.
• SAVEPOINT SAVEPOINT_NAME;
SQL Stored Procedures
SQL Stored Procedures
• A procedure (often called a stored procedure) is a collection of pre-
compiled SQL statements stored inside the database.
• It is a subroutine or a subprogram in the regular computing language. A
procedure always contains a name, parameter lists, and SQL statements.
• It is collection of MySQL statements grouped together in a function that
can be called on-demand with specific input parameters.
• With these, you get to reuse the code and Lesser Network transfer – E.g.
for web applications -instead of calling individual queries, a procedure that
can directly return the desired result can be executed.
• More secure – The Database Administrator can GRANT or REVOKE privileges
at a procedure level.
• Delimiter //
SQL Stored Procedures • CREATE PROCEDURE procedure
name(parameters)
• BEGIN
• The name of the procedure must be • statements;
specified after the Create Procedure
keyword • END //
• After the name of the procedure, the list of • Delimiter;
parameters must be specified in the
parenthesis. The parameter list must be
comma-separated • In MySQL, we use a semicolon (;)
• The SQL Queries and code must be written
as a default delimiter to separate
between BEGIN and END keywords the statements and execute them
separately.
• Delimiters are used when we need
to define the stored procedures as well as
to create triggers.
Why Do We Need Delimiter?
• When you write an individual statement you will need only a semicolon at the end of the
statement.
• But what if you want to write a block of statements that works as a single unit? In that
case, you will need to change the delimiter.
• In MySQL, stored procedures, functions and triggers are the blocks of statements where
you need the delimiter other than the default semicolon. The delimiter helps MySQL to
acknowledge the group of statements as a single unit or single task. However, the
individual statements in the blocks end with semicolons.
• If you are considering multiple statements, then you need to use different delimiters like $
$ or //.
• How To Change the Delimiter?
• You can change the delimiter by using the DELIMITER keyword.
• DELIMITER delimiter_character;
• The delimiter_character must be an unreserved character in MySQL for example, // , $$,
## etc.
Create Procedure Example
use company;
DELIMITER //
CREATE PROCEDURE viewEmployees()
BEGIN
SELECT * FROM Employee;
END //
DELIMITER ;
DELIMITER &&
CREATE PROCEDURE get_merit_student ()
BEGIN
SELECT * FROM studentinfo WHERE marks > 70;
END &&
DELIMITER ;
Create Procedure Example
• Procedures with Parameter
• DELIMITER &&
• CREATE PROCEDURE get_student (IN var1 INT)
• BEGIN
• SELECT * FROM studentinfo LIMIT var1;
• END &&
• DELIMITER ;
• DELIMITER &&
• CREATE PROCEDURE display_max_mark (OUT highestmark INT)
• BEGIN
• SELECT MAX(marks) INTO highestmark FROM studentinfo;
• END &&
• DELIMITER ;
• @M is Session vaiable
SQL Function
• A function in MySQL is a subprogram that is used to perform an action such as complex
calculations and returns the result of the action as a value. There are two types of functions
available in MySQL. They as follows:
1.System Defined Function
2.User-Defined Function
• The functions which are already defined or predefined by MySQL and ready to be used by
the developer are called as system-defined function whereas if the function is defined by
the developer, then such functions are called as a user-defined function.
1.Some functions take parameters; do some processing and returning some results back. For
example, SELECT SQRT(16); will return the square root of 16 i.e. 4.
2.Some functions do not take any parameters but return some results back. For
example, SELECT NOW(); will return the current date-time like 2021-07-09 07:11:07.
SQL Function
• How to Create User-Defined Functions
• First, we need to specify the name of the user-defined function
• Second, list all the input parameters of the user-defined
function
• Third, specify the data type of the return value in the RETURNS
statement.
• Fourth, specify if the function is deterministic or not
• If we don’t specify MySQL uses the NOT DETERMINISTIC option.
A deterministic function in MySQL always returns the same
result for the same input parameters whereas a non-
deterministic function returns different results for the same
input parameters.
• Fifth, write the code in the body of the user-defined function
within the BEGIN & END block.
SQL Function
• Create a Function in MySQL which
should return the cube of a given
value.
• How to Call a User Defined
Function in MySQL?
DELIMITER $$
SQL Function CREATE FUNCTION Func_Calculate_Age
• Create a User-defined Function in (
MySQL to calculate the age. Age date
• Let us create a user-defined stored )
function that will calculate and RETURNS INT DETERMINISTIC
returns the age of an employee. To
compute the age, we require the BEGIN
date of birth. DECLARE TodayDate DATE;
SELECT CURRENT_DATE() INTO
TodayDate;
RETURN YEAR(TodayDate) - YEAR(Age);
END$$
DELIMITER ;
Functions Vs Stored Procedures
Function Stored Procedure
Always returns a single value; either scalar or a table. Can return zero, single or multiple values.
Functions are compiled and executed at run time. Stored procedures are stored in parsed and
compiled state in the database.
Only Select statements. DML statements like update & Can perform any operation on database objects
insert are not allowed. including select and DML statements.
Allows only input parameters. Does not allow output Allows both input and output parameters
parameters.
Does not allow the use of Try…Catch blocks for exception Allows use of Try…Catch blocks for exception
handling. handling.
Cannot have transactions within a function. Can have transactions within a stored procedure.
Cannot call a stored procedure from a function. Can call a function from a stored procedure.
Functions can be called from a Select statement. Stored procedures cannot be called from a
Select/Where or Having statements. Execute
statement has to be used to execute a stored
procedure.
Functions can be used in JOIN clauses. Stored procedures cannot be used in JOIN clauses
Triggers in SQL
• Triggers are a set of SQL statements which are stored in the database catalog.
These statements are executed whenever an event associated with a table
occurs.
• So, a trigger can be invoked either BEFORE or AFTER the data is changed
by INSERT, UPDATE or DELETE statement.
• Before Insert: It is activated before the insertion of data into the table.
• After Insert: It is activated after the insertion of data into the table.
• Before Update: It is activated before the update of data in the table.
• After Update: It is activated after the update of the data in the table.
• Before Delete: It is activated before the data is removed from the table.
• After Delete: It is activated after the deletion of data from the table.
Triggers in SQL Use Student;
CREATE TABLE employee(
• Syntax:
name varchar(45) NOT NULL,
CREATE TRIGGER trigger_name
occupation varchar(35) NOT NULL,
(AFTER | BEFORE) (INSERT | UPDATE | DELETE) working_date date,
ON table_name FOR EACH ROW working_hours varchar(10)
BEGIN );
--variable declarations
--trigger code
END; INSERT INTO employee VALUES ('Robin', 'Scientist', '2020-10-04', 12),
('Warner', 'Engineer', '2020-10-04', 10), ('Peter', 'Actor', '2020-10-04', 13),
('Marco', 'Doctor', '2020-10-04', 14),('Brayden', 'Teacher', '2020-10-04', 12),
('Antonio', 'Business', '2020-10-04', 11);
Triggers in SQL
• we will create a BEFORE INSERT
trigger. This trigger is invoked
automatically insert
the working_hours = 0 if
someone tries to
DELIMITER //
insert working_hours < 0.
Create Trigger before_insert_empworkinghours
BEFORE INSERT ON employee FOR EACH ROW
BEGIN
IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;
END IF;
END //
DELIMITER ;
Views in SQL
• VIEW is a database object that can be created like a table. In SQL, a VIEW is
similar to a virtual table. But unlike tables VIEWS don’t actually store data.
• For security purposes, we can restrict users from accessing underlying
tables and instead give access to views or virtual tables with limited
columns.
• Since, every time user request view, the database engine recreates the
result set, which always returns up-to-date data rows from views.
Views in SQL
• Table Vs View
1.The table is physical i.e. it is an actual table whereas the view is logical i.e.
it is a virtual table.
2.A Table is an independent object whereas a view is a dependent object.
3.The Table stores the actual data of the database whereas View creates a
logical subset of data from one or more tables.
4.When a new table is created from an existing table, the new and old tables
are independent themselves, that is the changes of one table will not be
reflected into the other table whereas if a view is created based on a table,
any changes that are performed on the table will reflect into the view and
any changes performed on the view reflected in the table also.
Use Student;
Views in SQL • -- Create Employee Table
CREATE TABLE Employee1
• -- Populate the Employee Table with test data
(
• INSERT INTO Employee VALUES(1, 'Pranaya', 1, 20000, 'IT'); Id INT PRIMARY KEY,
• INSERT INTO Employee VALUES(2, 'Priyanka', 2, 30000, 'HR'); Name VARCHAR(50),
GenderId VARCHAR(50),
• INSERT INTO Employee VALUES(3, 'Anurag', 1, 40000, 'IT'); Salary INT,
• INSERT INTO Employee VALUES(4, 'Preety', 2, 25000, 'HR'); Department VARCHAR(50)
);
• INSERT INTO Employee VALUES(5, 'Sambit', 3, 35000, 'INFRA');
• INSERT INTO Employee VALUES(6, 'Hina', 2, 45000, 'HR');