Unit 3 Query Languages
Unit 3 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
• 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
• 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)
AND and OR Conjunctive Operators
• The SQL AND & OR operators are used to combine multiple conditions to narrow data
in an SQL statement. These two operators are called as the conjunctive operators.
• These operators provide a means to make multiple comparisons with different
operators in the same SQL statement.
• Q: Find Names of all CUSTOMERs , where the salary is
greater than 2000 and the age is less than 25 years .
• ᴨ Name [σSalary>2000 and Age<25 (Customer)]
Other The selection operation is also known as The Project operation is also known as vertical
1. Names horizontal partitioning. partitioning.
Which used The selection operation is performed before The projection operation is performed after
4. first projection (if they are to be used together). selection (if they are to be used together).
• 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 Text Data type example
SQL Datatype
Data type Description
• 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);
Finding second highest salary through nested
query
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;
Difference between Grant and Revoke
S.NO GRANT REVOKE
1 GRANT command is used to give access The REVOKE command does just opposite to the
privileges to the users or other rights GRANT command. It withdraws user privileges on
or opportunities for the database. database objects.
• 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;
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
• After the name of the procedure, the list of • END //
parameters must be specified in the • Delimiter;
parenthesis. The parameter list must be
comma-separated
• The SQL Queries and code must be written • In MySQL, we use a semicolon (;)
between BEGIN and END keywords as a default delimiter to separate
• Delimiters are used when we need to define the statements and execute them
the stored procedures as well as to create separately.
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
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.
SN Parameters Triggers Procedures
A Procedure is explicitly called by the
A Trigger is implicitly invoked whenever any event such
1. Basics user/application using statements or commands such
as INSERT, DELETE, or UPDATE occurs in a TABLE. as exec, EXECUTE, or simply procedure name
2. Action
When an event occurs, a trigger helps to execute an A procedure helps to perform a specified task when it
action automatically. is invoked.
3. Define/ call
Only nesting of triggers can be achieved in a table. We We can define/call procedures inside another
cannot define/call a trigger inside another trigger. procedure.
4. Syntax
In a database, the syntax to define a trigger: CREATE In a database, the syntax to define a procedure:
TRIGGER TRIGGER_NAME CREATE PROCEDURE PROCEDURE_NAME
5.
Transaction Transaction statements such as COMMIT, ROLLBACK, and All transaction statements such as COMMIT and
statements SAVEPOINT are not allowed in triggers. ROLLBACK are allowed in procedures.
6. Usage
Triggers are used to maintain referential integrity by Procedures are used to perform tasks defined or
keeping a record of activities performed on the table. specified by the users.
7. Return value
We cannot return values in a trigger. Also, as an input, We can return 0 to n values. However, we can pass
we cannot pass values as a parameter. values as parameters.
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
insert working_hours < 0.
DELIMITER //
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,
Name VARCHAR(50),
• INSERT INTO Employee VALUES(2, 'Priyanka', 2, 30000, 'HR'); GenderId VARCHAR(50),
• INSERT INTO Employee VALUES(3, 'Anurag', 1, 40000, 'IT'); Salary INT,
Department VARCHAR(50)
• INSERT INTO Employee VALUES(4, 'Preety', 2, 25000, 'HR');
);
• INSERT INTO Employee VALUES(5, 'Sambit', 3, 35000, 'INFRA');
• INSERT INTO Employee VALUES(6, 'Hina', 2, 45000, 'HR');