Overview of Query Languages and Algebra
Overview of Query Languages and Algebra
• 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, Assertions,
roles and privileges
• Embedded SQL, Dynamic SQL.
Algebra
• Algebra is the branch of mathematics that helps in the representation
of problems or situations in the form of mathematical expressions.
• For e.g. If the area of the rectangle is 36 cm2. Its length is represented
as l and width is represented as b. Then this statement is represented as :
l × b = 36
• BoB wants to visit a zoo. A ticket for the entry to the zoo cost [Link] has
only 3. How much more money does he need to buy the ticket?
• y=4−3 y=1
Algebra
• Abstract algebra, Linear algebra, and Boolean algebra
• Abstract algebra is the set of advanced topics of algebra that deal with
abstract algebraic structures rather than the usual number systems. The most
important of these structures are groups(Closure:Identity:Inverse:
Associativity: The defined multiplication is associative, i.e., for all A,B,C in G,
(AB)C=A(BC).),rings, and fields. It's used in computer science for secure
communication, in physics to understand symmetries and conservation laws,
and in engineering to design error-correcting codes.
• Linear algebra is the study of linear combinations. It is the study of vector
spaces, lines and planes, and some mappings that are required to perform the
linear transformations. It includes vectors, matrices and linear functions.
• Boolean algebra is a branch of mathematics that deals with operations on
logical values with binary variables. Applications are digital circuit
design,pocket calculator,CD Palyer,Cell Phone and other electronic products.
Relational Algebra
• 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.
• The relational algebra provides basic operations which can be performed over
single or multiple relations in order to generate new relations(single or
multiple).
• 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 : σ 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)]
• 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, Assertions,
roles and privileges
• Embedded SQL, Dynamic SQL.
What is SQL?
• 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.
Data type Description
It has a maximum length of 8000 characters. It contains Fixed-length non-unicode
char
characters.
It has a maximum length of 8000 characters. It contains variable-length non-
varchar
unicode characters.
It has a maximum length of 2,147,483,647 characters. It contains variable-length
text
non-unicode characters.
Datatype Description
date It is used to store the year, month, and days value.
time It is used to store the hour, minute, and second values.
timestamp It stores the year, month, day, hour, minute, and the second value.
SQL Datatype
Data type Description
• 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, Assertions,
roles and privileges
• Embedded SQL, Dynamic SQL.
Data Definition Language (DDL) : Let us Create Table
• 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, Assertions,
roles and privileges
• Embedded SQL, Dynamic SQL.
Data Query Language
• SELECT
• This statement is used to select data from a database and the data returned
is stored in a result table, called the result-set.
• Syntax : SELECT Column1, Column2, ...ColumN FROM TableName;
• SELECT * FROM table_name;
• Example: SELECT EmployeeID, EmployeeName FROM Employee;
• --(*) is used to select all from the table
• SELECT * FROM Employee;
• -- To select the number of records to return use:
• SELECT TOP 3 * FROM Employee;
Select Queries
• Filtering with WHERE
• Basic Queries • Active Employees Only
• Select All Employees SELECT emp_name, is_active
SELECT * FROM FROM Employee
Employee; WHERE is_active = b'1';
• Select Specific • Employees from a Specific City
Columns SELECT emp_name, city
FROM Employee
SELECT emp_name, WHERE city = 'Pune';
salary, designation • Employees with Salary > 60000
FROM Employee;
SELECT emp_name, salary
FROM Employee
WHERE salary > 60000;
Select Queries • NULL and DEFAULTs
• Employees Without Phone
• Working with Dates Numbers
• Employees Born After
1990 SELECT emp_name
SELECT emp_name, DOB FROM Employee
FROM Employee WHERE phone_num IS NULL;
WHERE DOB > '1990-01- • Show Employees with is_active as
01'; 'Yes'/'No'
• Compute Age on the Fly SELECT emp_name,
(if no age column exists) CASE is_active
SELECT emp_name, DOB, WHEN b'1' THEN 'Yes'
TIMESTAMPDIFF(YEAR,
DOB, CURDATE()) AS ELSE 'No'
computed_age END AS Active_Status
FROM Employee;
FROM Employee;
Select Queries • Conditional Logic
• Average Salary by • Label Experience Level
Designation SELECT emp_name,
SELECT designation, experience_years,
AVG(salary) AS CASE
avg_salary WHEN experience_years >= 15
FROM Employee THEN 'Senior'
GROUP BY designation; WHEN experience_years >= 5
THEN 'Mid-Level'
ELSE 'Junior'
END AS experience_level
FROM Employee;
Data Manipulation Language
• You can use the following keywords with the SELECT statement:
• DISTINCT
• ORDER BY
• GROUP BY
• HAVING Clause
• The ‘SELECT DISTINCT’ Statement
• This statement is used to return only different values.
• Syntax: SELECT DISTINCT Column1, Column2, ...ColumnN
FROM TableName;
• Example SELECT DISTINCT is_active FROM Employee;
Data Manipulation Language
• The ‘ORDER BY’ Statement
• The ‘ORDER BY’ statement is used to sort the required results in
ascending or descending order. The results are sorted in
ascending order by default.
• Syntax: SELECT Column1, Column2, ...ColumnN FROM
TableName ORDER BY Column1, Column2, ... ASC|DESC;
• SELECT emp_name, salary
• FROM Employee
• ORDER BY salary DESC
• LIMIT 5; --Top 5 Highest Paid Employees
Data Manipulation Language
• The ‘GROUP BY’ Statement
• This ‘GROUP BY’ statement is used with the aggregate functions to
group the result-set by one or more columns.
• Syntax :SELECT Column1, Column2,..., ColumnN
• FROM TableName
• WHERE Condition
• GROUP BY ColumnName(s)
• ORDER BY ColumnName(s);
• Example Count Employees by Blood Group
• SELECT blood_group, COUNT(*) AS total
• FROM Employee
• GROUP BY blood_group;
Data Manipulation Language
• The ‘HAVING’ Clause
• Syntax : SELECT ColumnName(s)
• FROM TableName
• WHERE Condition
• GROUP BY ColumnName(s)
• HAVING Condition
• ORDER BY ColumnName(s);
• Example /* Count Employees by Blood Group > 2:*/
• SELECT COUNT(*), blood_group
• FROM Employee
• GROUP BY blood_group
• HAVING COUNT(blood_group) > 2
• ORDER BY COUNT(blood_group) DESC;
Group by and Having Clause Examples
• 1. Group Employees by Designation • 3. Count of Employees in Each
and Show Average Salary City
SELECT designation, AVG(salary) AS SELECT city, COUNT(*) AS
avg_salary FROM Employee employee_count FROM Employee
GROUP BY designation; GROUP BY city;
• 2. Show Designations With Average • 4. Cities with More Than 5
Salary Above ₹60,000 (Using Employees
HAVING) SELECT city, COUNT(*) AS
SELECT designation, AVG(salary) AS employee_count FROM Employee
avg_salary FROM Employee GROUP BY city
GROUP BY designation HAVING COUNT(*) > 5;
HAVING AVG(salary) > 60000;
Group by and Having Clause Examples
• 5. Group by Blood Group with • 7. Show Total Salary per Country Where
Total > ₹200,000
Minimum Bonus > ₹4000
SELECT Country, SUM(salary) AS total_salary
SELECT blood_group,
MIN(bonus_amount) AS min_bonus FROM Employee
FROM Employee GROUP BY Country
GROUP BY blood_group HAVING SUM(salary) > 200000;
HAVING MIN(bonus_amount) > 4000; • 8. Employees Grouped by Active/Inactive
Status
SELECT
• 6. Group by Project Count and Show CASE is_active
Average Experience
WHEN b'1' THEN 'Active'
SELECT project_count, ELSE 'Inactive'
AVG(experience_years) AS
avg_experience END AS status,
FROM Employee COUNT(*) AS total
GROUP BY project_count; FROM Employee
GROUP BY is_active;
WHERE HAVING
It is used to filter data directly It is used to filter the data of
on the table groups created on a table.
It is applied as a row It is applied as a column
operation. operation.
The WHERE clause pulls only The HAVING clause fetches all
the filter data based on data before applying the filter
condition. Filter rows before condition. Filter groups after
grouping aggregation
You cannot use aggregate It is used on aggregate
functions on the WHERE function on which group has
condition. performed.
Having and Where Clause Example
• List the book
details whose
price is less than
350 [Table 1]
• Identify language
and count number
of books for the
language having
multiple books.
Aggregate Functions
• An aggregate function in SQL performs a • MAX() Function
calculation on multiple values and returns
a single value. • The MAX function returns
• SQL provides many aggregate functions the largest value of the
that include avg, count, sum, min, max, selected column in a table.
etc.
• Syntax
• An aggregate function ignores NULL
values when it performs the calculation, • SELECT MAX(ColumnName)
except for the count function.
• MIN() Function • FROM TableName
• The MIN function returns the smallest • WHERE Condition;
value of the selected column in a table.
• Syntax
• SELECT MIN(ColumnName)
• FROM TableName
• WHERE Condition;
Aggregate Functions • AVG() Function
• The AVG function returns the
• COUNT() Function average value of a numeric
• The COUNT function returns the column that you choose.
number of rows which match the
specified criteria. • Syntax SELECT
AVG(ColumnName)
• Syntax: SELECT COUNT(ColumnName)
FROM TableName • FROM TableName WHERE
• WHERE Condition; Condition;
• SUM() Function
• The SUM function returns the total
sum of a numeric column that you
choose.
• Syntax: SELECT SUM(ColumnName)
FROM TableName WHERE Condition;
Select Queries With Aggregate Functions
• 1. Total Number of Employees
SELECT COUNT(*) AS total_employees FROM Employee;
Null Whether the column can be NULL (YES or empty for NOT NULL)
• Update salary of an
employee with 0.25%
whose age is greater than
or equal to 29.
Data Control Language
• Data Control Language (DCL) in SQL is used to control access
and permissions for users in a database. DCL is mainly about
security & permissions.
• Commands that come under DCL: Grant, Revoke
• Grant: Gives specific privileges to a user or role.
• GRANT privilege_list ON object_name TO user_name;
• -- Give SELECT and UPDATE permission on Employee table to user
‘root’
• GRANT SELECT, UPDATE ON Employee TO ‘root'@'localhost’;
• Apply Changes
• FLUSH PRIVILEGES;
• This reloads the privileges from the MySQL grant tables.
Difference between Grant and Revoke
[Link] 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.
• 3. ROLLBACK
• Undoes all changes made in the current transaction.
• ROLLBACK;
Transaction Control Language
• 4. SAVEPOINT
• Creates a point inside a transaction that you can roll back
to without affecting earlier work.
• SAVEPOINT sp1;
• 5. ROLLBACK TO SAVEPOINT
• Rolls back to a specific savepoint.
• ROLLBACK TO SAVEPOINT sp1;
• 6. RELEASE SAVEPOINT
• Deletes a savepoint (so it can’t be rolled back to later).
• RELEASE SAVEPOINT sp1;
Transaction Control Language
• COMMIT
DELETE FROM CUSTOMERS
WHERE AGE = 25;
COMMIT;
• ROLLBACK
DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
• Rollback: Rollback command is used to undo transactions that
have not already been saved to the database.
• SAVEPOINT: It is used to roll the transaction back to a certain
point without rolling back the entire transaction.
• SAVEPOINT SAVEPOINT_NAME;
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 • -- Step 3: Set a
SAVEPOINT after salary
• -- Step 1: Start the transaction update
• START TRANSACTION; • SAVEPOINT
after_salary_update;
• --Turns off autocommit and • --Marks this stage so we
begins a transaction. can come back to it if
needed.
• 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, Assertions,
roles and privileges
• Embedded SQL, Dynamic SQL.
SQL Commands: Set Operations
• The SET Operators in MySQL are basically used to combine the result of more than 1
select statement and return the output as a single result set. In SQL, 4 types of set
operators are. They are as follows:
[Link]: It is used to combine two or more result sets into a single set, without
duplicates.
[Link] ALL: It is used to combine two or more result sets into a single set, including
duplicates.
[Link]: It is used to combine two result sets and returns the data which are
common in both the result set.
[Link]/MINUS: It is used to combine two result sets and returns the data from the first
result set which is not present in the second result set.
• Points to Remember while working with Set Operations:
[Link] SELECT statement involved in the query must have a similar number of columns.
[Link] columns in the SELECT statement must be in the same order and have similar data
types.
[Link] order to sort the result, an ORDER BY clause should be part of the last select statement.
The column names or aliases must be found out by the first select statement.
SQL Commands: Set Operations
• To perform SET operations (like UNION, INTERSECT, EXCEPT)
with the existing Employee table, we’ll create another related table.
• For example, a Department table or a second employee-like table.
CREATE TABLE Employee_Copy (
Emp_ID INT PRIMARY KEY,
emp_name VARCHAR(300) NOT NULL,
phone_num BIGINT,
city VARCHAR(100),
Country VARCHAR(100),
salary DECIMAL(10,2),
designation VARCHAR(100)
);
Add Data into Employee_copy
• 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, Assertions,
roles and privileges
• Embedded SQL, Dynamic SQL.
SQL Commands: Join Operations
• To perform JOIN operations with the existing Employee table,
we’ll create another related table.
• For example, a Department table or a second employee-like
table.
CREATE TABLE Department (
dept_id INT AUTO_INCREMENT PRIMARY KEY,
dept_name VARCHAR(100) NOT NULL,
location VARCHAR(100),
manager_id INT,
FOREIGN KEY (manager_id) REFERENCES
Employee(Emp_ID)
);
Add Data to Department Table
• INSERT INTO Department (dept_name, location, manager_id)
• VALUES
• ('Human Resources', 'Mumbai', 1), -- Manager is Emp_ID = 1
• ('Finance', 'Pune', 3), -- Manager is Emp_ID = 3
• ('IT', 'Bengaluru', 5), -- Manager is Emp_ID = 5
• ('Sales', 'Delhi', 2), -- Manager is Emp_ID = 2
• ('Marketing', 'Chennai', 4); -- Manager is Emp_ID = 4
SELECT
e.emp_name AS employee,
m.emp_name AS manager
FROM Employee e
JOIN Employee m
ON e.Emp_ID = m.Emp_ID;
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, Assertions,
roles and privileges
• Embedded SQL, Dynamic SQL.
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
specified after the Create Procedure • statements;
keyword • END //
• After the name of the procedure, the list
of parameters must be specified in the • Delimiter;
parenthesis. The parameter list must be
comma-separated
• The SQL Queries and code must be • In MySQL, we use a semicolon (;)
written between BEGIN and END as a default delimiter to separate
keywords the statements and execute them
• Delimiters are used when we need separately.
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 ;
• CALL ShowEmployees();
Example : Show all Departments
DELIMITER $$
CREATE PROCEDURE ShowDepartments()
BEGIN
SELECT dept_id, dept_name, location
FROM Department;
END $$
DELIMITER ;
CALL ShowDepartments();
Example With IN Parameter: Show employees from a given city
DELIMITER $$
CREATE PROCEDURE GetEmployeesByCity(IN cityName VARCHAR(100))
BEGIN
SELECT Emp_ID, emp_name, city, designation, salary
FROM Employee
WHERE city = cityName;
END $$
DELIMITER ;
CALL GetEmployeesByCity('Pune');
Example With IN Parameter : Show departments managed
by a specific manager
DELIMITER $$
CREATE PROCEDURE GetDepartmentsByManager(IN managerId INT)
BEGIN
SELECT dept_id, dept_name, location
FROM Department
WHERE manager_id = managerId;
END $$
DELIMITER ;
CALL GetDepartmentsByManager(3);
Example With IN Parameter : Increase Employee Salary
DELIMITER $$
CREATE PROCEDURE IncreaseSalary (
IN p_emp_id INT,
IN p_increment DECIMAL(10,2)
)
BEGIN CALL IncreaseSalary(1, 2000);
UPDATE Employee
SET salary = salary + p_increment
WHERE Emp_ID = p_emp_id;
END $$
DELIMITER ;
Example With IN OUT Parameter: Get salary of an employee by ID
DELIMITER $$
CREATE PROCEDURE GetEmployeeSalary(
IN empId INT,
OUT empSalary DECIMAL(10,2)
)
BEGIN CALL GetEmployeeSalary(1, @sal);
SELECT salary SELECT @sal AS Employee_Salary;
INTO empSalary
FROM Employee
WHERE Emp_ID = empId;
END $$
DELIMITER ;
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:
[Link] Defined Function
[Link]-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.
[Link] 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.
[Link] 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
• What is DETERMINISTIC or NOT
DETERMINISTIC
• DETERMINISTIC
• A function always returns the same
output for the same input.
• Example: mathematical functions
(square(x), add(a,b))
• NON-DETERMINISTIC
• A function may return different results
even with the same input.
• Example: functions using NOW(),
RAND(), CURDATE(), etc.
Example : Get Age from DOB
-- Change the delimiter so we can use ; inside the function body
DELIMITER $$
DROP FUNCTION IF EXISTS GetAge $$
CREATE FUNCTION GetAge(dob DATE)
RETURNS INT SELECT emp_name, GetAge(DOB) AS
NOT DETERMINISTIC Age FROM Employee;
NO SQL
BEGIN
DECLARE age INT;
SET age = TIMESTAMPDIFF(YEAR, dob, CURDATE());
RETURN age;
END $$
-- Reset delimiter back to normal
DELIMITER ;
Example : Calculate Bonus
DELIMITER $$
CREATE FUNCTION CalculateBonus(salary DECIMAL(10,2), experience
INT)
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
DECLARE bonus DECIMAL(10,2);
SET bonus = salary * (experience * 0.05);
RETURN bonus;
END $$ SELECT emp_name, salary, CalculateBonus(salary,
DELIMITER ; experience_years) AS Bonus FROM Employee;
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
• The following are the main characteristics that
distinguish triggers from stored procedures:
• We cannot manually execute/invoked triggers.
• Triggers have no chance of receiving
parameters.
• A transaction cannot be committed or rolled
back inside a trigger.
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
When an event occurs, a trigger helps to execute an A procedure helps to perform a specified task when
2. Action
action automatically. it is invoked.
In a database, the syntax to define a trigger: CREATE In a database, the syntax to define a procedure:
4. Syntax
TRIGGER TRIGGER_NAME CREATE PROCEDURE PROCEDURE_NAME
Transaction Transaction statements such as COMMIT, ROLLBACK, and All transaction statements such as COMMIT and
5.
statements SAVEPOINT are not allowed in triggers. ROLLBACK are allowed in procedures.
Triggers are used to maintain referential integrity by Procedures are used to perform tasks defined or
6. Usage
keeping a record of activities performed on the table. specified by the users.
We cannot return values in a trigger. Also, as an input, We can return 0 to n values. However, we can pass
7. Return value
we cannot pass values as a parameter. values as parameters.
Triggers in SQL
• Syntax:
CREATE TRIGGER trigger_name
(AFTER | BEFORE) (INSERT | UPDATE | DELETE)
ON table_name FOR EACH ROW
BEGIN
--variable declarations
--trigger code
END;
Triggers in SQL :Auto-Calculate Age on INSERT
DELIMITER $$
CREATE TRIGGER before_employee_insert
BEFORE INSERT ON Employee
SELECT emp_name, DOB, age FROM
FOR EACH ROW Employee WHERE emp_name = 'Ravi
BEGIN Kumar';
IF [Link] IS NOT NULL THEN
SET [Link] = TIMESTAMPDIFF(YEAR,
[Link], CURDATE());
END IF;
INSERT INTO Employee (emp_name, phone_num, city, Country,
END $$ blood_group, salary, designation, DOB)
VALUES ('Ravi Kumar', 9376943210, 'Delhi', 'India', 'O+', 55000.00,
DELIMITER ; 'Engineer', '1995-05-10');
Triggers in SQL :Auto-Update Age on DOB Change
DELIMITER $$
CREATE TRIGGER before_dob_update
BEFORE UPDATE ON Employee
FOR EACH ROW
BEGIN
IF [Link] <> [Link] THEN
SET [Link] = TIMESTAMPDIFF(YEAR,
[Link], CURDATE());
END IF;
END $$
DELIMITER ;
Triggers in SQL :Prevent Deletion of a Department with Employees
DELIMITER $$
CREATE TRIGGER prevent_dept_delete
BEFORE DELETE ON Department
FOR EACH ROW
BEGIN
IF EXISTS (SELECT 1 FROM Employee WHERE Emp_ID = OLD.manager_id)
THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Cannot delete department: Manager still exists in
Employee table';
END IF;
END $$
DELIMITER ;
View Procedures, Functions, And Triggers
• SHOW PROCEDURE STATUS WHERE Db = 'semi25_26';
• SHOW FUNCTION STATUS WHERE Db = 'semi25_26';
• SHOW TRIGGERS FROM semi25_26;
• 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,
Assertions, roles and privileges
• Embedded SQL, Dynamic SQL.
Mapping of Relational Algebra to SQL
• σ → WHERE
• π → SELECT cols
• ρ → AS
• , −, ∩ → UNION, EXCEPT, INTERSECT (or
JOIN tricks in MySQL)
• × → CROSS JOIN
• → JOIN
• ÷ → Nested queries
Mapping of Relational Algebra to SQL
Relational
SQL
Algebra Example (Employee Table)
Equivalent
Operation
Selection (σ) Select
RA: σ salary > 50000 (Employee) SQL:
rows satisfying a WHERE clause
SELECT * FROM Employee WHERE salary > 50000;
condition
Projection (π) Select SELECT
RA: π emp_name, salary (Employee) SQL:
certain attributes specific
SELECT emp_name, salary FROM Employee;
(columns) columns
Renaming (ρ)
RA: ρ(Emp)(Employee) SQL:
Rename AS alias
SELECT emp_name AS Name FROM Employee;
relation/attributes
Union ( ∪ ) Combine
RA: Employee ∪ Employee_Copy SQL: SELECT
rows from two
UNION emp_name FROM Employee UNION SELECT
relations (removes
emp_name FROM Employee_Copy;
duplicates)
Mapping of Relational Algebra to SQL
Relational
Algebra SQL Equivalent Example (Employee Table)
Operation
RA: Employee − Employee_Copy SQL (MySQL way): SELECT
EXCEPT (MySQL →
e.emp_name FROM Employee e LEFT JOIN Employee_Copy
Set Difference ( − ) simulate using LEFT JOIN
c ON e.emp_name=c.emp_name WHERE c.emp_name IS
+ WHERE NULL)
NULL;
RA: Employee ∩ Employee_Copy SQL (MySQL way): SELECT
INTERSECT (MySQL →
Intersection ( ∩ ) e.emp_name FROM Employee e INNER JOIN
simulate with INNER JOIN)
Employee_Copy c ON e.emp_name=c.emp_name;
RA: Employee × Department SQL: SELECT * FROM
Cartesian Product (×) CROSS JOIN
Employee CROSS JOIN Department;
RA: Employee ⨝ Department (Emp_ID = manager_id) SQL:
INNER JOIN, LEFT JOIN,
Join (⨝) SELECT e.emp_name, d.dept_name FROM Employee e JOIN
etc.
Department d ON e.Emp_ID=d.manager_id;
RA: A ÷ B SQL: SELECT A.emp_id FROM WorksOn A
Division (÷) (find tuples Nested queries with NOT
WHERE NOT EXISTS (SELECT * FROM Project B WHERE
related to all tuples in EXISTS or GROUP BY
NOT EXISTS (SELECT * FROM WorksOn C WHERE
another relation) HAVING COUNT
C.emp_id=A.emp_id AND C.proj_id=B.proj_id));
Example with Employee Tables
• 1. Selection (σ)
• SELECT * FROM Employee WHERE city = 'Pune';
• 2. Projection (π)
• SELECT emp_name, salary FROM Employee;
• 3. Union
• SELECT emp_name FROM Employee
• UNION
• SELECT emp_name FROM Employee_Copy;
• 4. Join
• SELECT e.emp_name, d.dept_name
• FROM Employee e
• JOIN Department d ON e.Emp_ID = d.manager_id;
What is an Assertion in SQL?
• An assertion is a condition (rule) that must always hold true for
the database or It’s integrity constraints in SQL.
• If any operation (INSERT/UPDATE) violates it, the DBMS rejects
the change.
• MySQL does not support CREATE ASSERTION (only Oracle,
PostgreSQL, etc. support it partially).
• Assertions are defined using the CREATE ASSERTION statement
and include a CHECK clause that specifies the condition to be
enforced.
• If any database operation (such as INSERT, UPDATE, or DELETE)
would cause the assertion's condition to become false, the
operation is prevented, and an error is typically returned.
• Assertions are used to maintain data consistency and validity by
preventing operations that would lead to an invalid database state
according to defined business rules.
Assertion in SQL?
• Syntax (Standard SQL):
• CREATE ASSERTION assertion_name CHECK ( condition );
• Example Assertions
• 1. Salary must be greater than 0(Standard SQL)
• CREATE ASSERTION salary_positive
• CHECK (NOT EXISTS (
• SELECT * FROM Employee WHERE salary <= 0
• ));
• MySQL Equivalent → Use CHECK constraint
• ALTER TABLE Employee ADD CONSTRAINT chk_salary CHECK (salary > 0);
Assertion for An Employee’s Age must match DOB (Auto-calculated)
• MySQL Equivalent using Trigger:
• Standard SQL Assertion:
• DELIMITER $$
• CREATE ASSERTION • CREATE TRIGGER age_check
• BEFORE INSERT ON Employee
emp_age_check
• FOR EACH ROW
• CHECK (NOT EXISTS ( • BEGIN
• SELECT * FROM Employee • IF TIMESTAMPDIFF(YEAR, [Link],
CURDATE()) <> [Link] THEN
• WHERE TIMESTAMPDIFF(YEAR, • SIGNAL SQLSTATE '45000'
DOB, CURDATE()) <> age • SET MESSAGE_TEXT = 'Age does not
match DOB!';
• ));
• END IF;
• END$$
• DELIMITER ;
Roles and Privileges
• 1. What are Privileges?
• Privileges are the rights or permissions given to a user to
perform certain operations on the database.
• Examples:
• SELECT, INSERT, UPDATE, DELETE → Data operations
• CREATE, DROP, ALTER → Schema operations
• GRANT, REVOKE → Control access
• 2. What are Roles?
• A Role is a named collection of privileges that can be
assigned to one or more users.
Working with Roles & Privileges
• Create a User
CREATE USER ‘root'@'localhost' IDENTIFIED BY ‘root';
• Create a Role
CREATE ROLE 'hr_role’;
CREATE ROLE 'manager_role';
• Grant Privileges to a Role
• -- HR can only view employee data
GRANT SELECT ON Employee TO 'hr_role';
• -- Manager can update salaries
GRANT UPDATE(salary) ON Employee TO 'manager_role';
Working with Roles & Privileges
• Assign Role to a User
GRANT 'hr_role' TO ‘root'@'localhost';
• Activate Role for a Session
SET ROLE 'hr_role';
• Grant All Privileges (Super User)
• --WITH GRANT OPTION → allows this user to give their
privileges to others
GRANT ALL PRIVILEGES ON *.* TO 'admin_user'@'localhost'
WITH GRANT OPTION;
Working with Roles & Privileges
• Revoke Privileges / Roles
REVOKE UPDATE ON Employee FROM 'manager_role';
REVOKE 'hr_role' FROM ‘root'@'localhost';
• View Privileges
• --Show user’s privileges:
SHOW GRANTS FOR ‘root'@'localhost’;
• --Show role privileges:
SHOW GRANTS FOR 'hr_role';
Working with Roles & Privileges-Employee–Department
Database
• Create roles
• CREATE ROLE 'employee_reader', 'department_manager’;
• Assign privileges
• -- Employee reader can only view employees
• GRANT SELECT ON Employee TO 'employee_reader';
• -- Department manager can insert and update departments
• GRANT INSERT, UPDATE ON Department TO 'department_manager’;
• Assign to users
• CREATE USER 'john'@'localhost' IDENTIFIED BY 'john123';
• CREATE USER 'alice'@'localhost' IDENTIFIED BY 'alice123';
• GRANT 'employee_reader' TO 'john'@'localhost';
• GRANT 'department_manager' TO 'alice'@'localhost';
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,
Assertions, roles and privileges
• Embedded SQL, Dynamic SQL.
Embedded SQL
• How is SQL Statement Processed?
Embedded SQL
• Embedded SQL is a method that allows the integration of
SQL statements directly within the source code of a high-
level programming language, often referred to as a "host
language" (e.g., C, C++, COBOL, Fortran).
• This approach enables developers to combine the
computational power of a programming language with the
data manipulation capabilities of SQL.
• Embedded SQL, often called static SQL, refers to SQL
statements that are fixed in an application and can’t be
modified at runtime. Only at compile time these statements
get compiled.
Structure of Embedded SQL
• Connection to the database:
• Connection to the database to be
established first, it can be done either by
using any specific function provided by
the programming language or any
specific Database Management library.
• The CONNECT keyword may be accustomed
do that. It should, however, be preceded
with ‘EXEC SQL’ to specify the SQL
statement.
• EXEC SQL CONNECT db_name;
• EXEC SQL CONNECT HR_USER;
//connects to DB HR_USER
Structure of Embedded SQL
• Declaration Section: The declaration section is used to declare
variables that will be used in SQL queries and to capture the
results of those queries. Types of variables used in the host
language are:
• Host Variable: Host variables are variables of the host language
that are used to supply data and store the results of SQL queries.
The BEGIN DECLARE and END DECLARE sections are defined
within EXEC SQL and should be used to declare the variables
within the SQL code.
• EXEC SQL BEGIN DECLARE SECTION;
• int id;
• int roll_no;
• char name[10];
• char address[30];
• EXEC SQL END DECLARE SECTION;
• To indicate that the host variable could be a dynamic host, it
should be preceded by a colon — ‘:’ within the SQL query.
• EXEC SQL SELECT * FROM STUDENT WHERE STUDENT_ID
=:STD_ID;
Structure of Embedded SQL
• Indicator variables: Indicator variables are also
host variables but they are used to capture NULL
values which are returned by queries or to set
NULL values in INSERT or UPDATE statements.
• EXEC SQL SELECT NAME INTO :NAME
:IND_NAME FROM STUDENT WHERE ID = :ID;
• INSERT INTO STUDENT (ID, SNAME) VALUES
(:ID, :NAME :IND_NAME);
• UPDATE STUDENT SET ADDRESS = :ADDRESS
:IND_ADDRESS;
Structure of Embedded SQL
• Execution Section
• The execution section contains all the SQL queries and
statements that are prefixed by EXEC SQL.
• EXEC SQL SELECT * FROM STUDENT WHERE
STUDENT_ID = :STD_ID;
• Error Handling
• In embedded SQL, error handling is based on the host
language. In C programs, error handling is typically done
using labels and the WHENEVER statement. The
WHENEVER statement is used to define the action to be
taken when a certain condition occurs.
• The condition can be SQLWARNING, SQLERROR, or NOT
FOUND. The action can be CONTINUE, DO <function>,
GOTO , or STOP.
• Example
• EXEC SQL WHENEVER SQLWARNING DO
display_warning();
• EXEC SQL WHENEVER SQLERROR STOP;
• EXEC SQL WHENEVER NOT FOUND GOTO lbl_no_records;
Select Employees in C with Embedded SQL
#include <stdio.h> int main() {
#include <stdlib.h> /* Connect to the database */
#include <string.h> EXEC SQL CONNECT TO ‘employee'
/* Include SQL communications area USER 'root' IDENTIFIED BY ‘root';
*/
EXEC SQL INCLUDE sqlca; if ([Link] != 0) {
/* Declare host variables */ printf("Connection failed! Error
EXEC SQL BEGIN DECLARE SECTION; code: %d\n", [Link]);
int emp_id; exit(1);
char emp_name[100]; }
char city[50]; printf("Connected to database
successfully!\n");
EXEC SQL END DECLARE SECTION;
Select Employees in C with Embedded SQL
/* Fetch rows one by one */
/* Declare a cursor for fetching while (1) {
Employee data */ EXEC SQL FETCH emp_cursor INTO :emp_id,
:emp_name, :city;
EXEC SQL DECLARE emp_cursor
if ([Link] == 100) { // 100 = no more
CURSOR FOR rows
SELECT Emp_ID, emp_name, city break;
FROM Employee; }
if ([Link] < 0) {
printf("Error while fetching data. Code:
/* Open the cursor */ %d\n", [Link]);
break;
EXEC SQL OPEN emp_cursor;
}
printf("ID: %d, Name: %s, City: %s\n",
emp_id, emp_name, city);
printf("\nEmployee Records:\n");
}
Select Employees in C with Embedded SQL
• EXEC SQL ... → Embedded SQL
/* Close the cursor */
commands inside C.
EXEC SQL CLOSE emp_cursor;
• Host variables → C variables
/* Disconnect */ (emp_id, emp_name, city) are
EXEC SQL COMMIT WORK bound to SQL query results.
RELEASE;
• Cursor → Used to fetch
return 0; multiple rows one by one.
}
• [Link] → Stores the
status of SQL execution (0 =
success, 100 = no data).
Dynamic SQL
• Dynamic SQL is SQL code that is built and executed at runtime instead
of being hard-coded in advance.
• Unlike static SQL, where queries are fixed during the development phase, dynamic SQL
enables developers to build flexible and general-purpose SQL queries that adapt to varying
conditions.
• Dynamic SQL can be executed using commands like EXEC or
sp_executesql.
• Static SQL
• SELECT emp_name, salary FROM Employee WHERE Emp_ID = 101;
• Dynamic SQL
• SET @sql = 'SELECT emp_name, salary FROM Employee WHERE
Emp_ID = ?';
• PREPARE stmt FROM @sql;
• SET @id = 101;
• EXECUTE stmt USING @id;
• DEALLOCATE PREPARE stmt;
Dynamic SQL
• When to Use Dynamic SQL
• Dynamic SQL is particularly useful in the following scenarios:
• When query structure varies significantly based on user
input or business logic, such as filtering reports by different
criteria.
• Example: Building a WHERE clause dynamically based on
user-selected filters.
• Generating reports where column selection, sorting, or
grouping criteria are dynamically specified.
• When querying multiple databases or dynamically choosing
databases during runtime based on certain conditions.
• Automating the creation or modification of database objects
(e.g., tables, indexes, stored procedures) programmatically.
Simple Dynamic SQL
• use sycsa;
• SET @sql = 'SELECT emp_name, salary FROM Employee WHERE
salary > 50000';
• PREPARE stmt FROM @sql;
• EXECUTE stmt;
• DEALLOCATE PREPARE stmt;
• SET @sql = ... putting query in a variable (@sql).
• PREPARE stmt FROM @sql: The query string inside @sql is
compiled into an executable statement and stored as stmt.
• EXECUTE stmt : Runs the prepared statement (stmt). At this
point, the SQL actually hits the database and returns results.
• DEALLOCATE PREPARE stmt : Cleans up memory by removing
the prepared statement.
Dynamic SQL with Parameter
• SET @sql = 'SELECT emp_name, salary FROM Employee WHERE salary > ?';
• PREPARE stmt FROM @sql;
• SET @min_salary = 40000;
• EXECUTE stmt USING @min_salary;
• DEALLOCATE PREPARE stmt;
Dynamic SQL with Parameter
• -- Step 1: Define a variable (threshold
salary)
• SET @min_salary = 60000; • -- Step 4: Execute the dynamic SQL
• -- Step 2: Build the SQL string • EXECUTE stmt;
dynamically
• SET @sql = CONCAT('SELECT Emp_ID,
emp_name, salary • -- Step 5: Free resources
• FROM Employee • DEALLOCATE PREPARE stmt;
• WHERE salary > ',
@min_salary);