Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Unit 3 Query Languages

The document discusses various query languages including relational algebra and SQL. It describes key operations in relational algebra like selection, projection, join, union, set difference and cartesian product. It provides examples of how each operation works and how it is expressed in SQL. Relational algebra operations like theta join, natural join, equi join, and outer joins are also explained.

Uploaded by

Yash Chaudhari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Unit 3 Query Languages

The document discusses various query languages including relational algebra and SQL. It describes key operations in relational algebra like selection, projection, join, union, set difference and cartesian product. It provides examples of how each operation works and how it is expressed in SQL. Relational algebra operations like theta join, natural join, equi join, and outer joins are also explained.

Uploaded by

Yash Chaudhari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

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)]

• Q: SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE


SALARY > 2000 OR age < 25;
• ᴨ ID,Name , Salary [σSalary>2000 Or Age<25 (Customer)]
S.
N Category Selection Projection
o.

Other The selection operation is also known as The Project operation is also known as vertical
1. Names horizontal partitioning. partitioning.

It is used to choose the subset of tuples from


2. Use the relation that satisfies the given condition It is used to select certain required attributes, while
discarding other attributes.
mentioned in the syntax of selection.

3. Partitioning It partitions the table horizontally. It partitions the table vertically.

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).

Column Select is used to select all columns of a


5 Project is used to select specific columns.
Selection specific tuple.
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
• 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 : 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 : Joins
• The database joins has the ability of
combining two or more data tables
into a single 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(Equi Joins)
• EQUI Join is done when a Theta join uses only the equivalence condition.
• EQUI JOIN creates a JOIN for equality or matching column(s) values of the
relative tables.
• For example:
• A ⋈ A.column 2 = B.column 2 (B)
• SELECT student.name, student.id, record.class, record.city FROM student JOIN
record ON student.city = record.city;
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+
common tuples from both tables.
• 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:

• For example : Consider the tables Student_Details and Student_Result. Now,


if we want to implement left outer join on these relations, the result will look
like:
Relational Algebra : Joins (The Outer Joins)
• Right Outer Join : In the right outer join, operation allows keeping all tuple
in the right relation.
• However, if there is no matching tuple is found in the left relation, then the
attributes of the left relation in the join result are filled with null values.

• For example : Consider the tables Student_Details and Student_Result. Now,


if we want to implement right outer join on these relations, the result will
look like:
Relational Algebra : Joins (The Outer Joins)
• Full Outer Join : In a full outer join, all tuples from both relations are
included in the result, irrespective of the matching condition.
• If in case, tuples doesn’t matches, NULL value is passes against that.

• For example : Consider the tables Student_Details and Student_Result. Now,


if we want to implement full outer join on these relations, the result will look
like:
• 1] List the names and age of students enrolled in different courses.  
• 2]Identify names of all students those who are admitted and not enrolled for
courses.
• 3] Identify names of students , those who belong to Bihar.
Relational Algebra:Summary

Operation (Symbols) Purpose


Select(σ) The SELECT operation is used for selecting a subset of the tuples according to a given selection
condition
Projection(π) The projection eliminates all attributes of the input relation but those mentioned in the
projection list.
Union Operation(∪) UNION is symbolized by symbol. It includes all tuples that are in tables A or in B.
Set Difference(-) The result of A – B, is a relation which includes all tuples that are in A but not in B.
Intersection(∩) Intersection defines a relation consisting of a set of all tuple that are in both A and B.
Cartesian Product(X) Cartesian operation is helpful to merge columns from two relations.
Inner Join Inner join, includes only those tuples that satisfy the matching criteria.
Theta Join(θ) The general case of JOIN operation is called a Theta join. It is denoted by symbol θ.
EQUI Join When a theta join uses only equivalence condition, it becomes a equi join.
Natural Join(⋈) Natural join can only be performed if there is a common attribute between the relations.
Outer Join In an outer join, along with tuples that satisfy the matching criteria.
Left Outer Join(  ) In the left outer join, operation allows keeping all tuple in the left relation.
Right Outer join( ) In the right outer join, operation allows keeping all tuple in the right relation.
Full Outer Join( ) In a full outer join, all tuples from both relations are included in the result irrespective of the
matching condition.
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.
• 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

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 Text Data type example
SQL Datatype
Data type Description

int It is used to specify an integer value.

smallint It is used to specify small integer value.

bit It has the number of bits to store.

decimal It specifies a numeric value that can have a decimal


number.
numeric It is used to specify a numeric value.
SQL Commands
• SQL commands are
instructions. It is used to
communicate with the
database. It is also used to
perform specific tasks,
functions, and queries of
data.
• SQL can perform various tasks
like create a table, add data
to tables, drop the table,
modify the table, set
permission for users.
• Comments in SQL
SQL Commands • Single-Line Comments
• The single line comment starts with two hyphens
• Data Definition Language(DDL) – (–). So, any text mentioned after (–), till the end
Consists of commands which are of a single line will be ignored by the compiler.
used to define the database. • Example:
• Data Manipulation Language(DML) • --Select all:
– Consists of commands which are • SELECT * FROM Employee_Info;
used to manipulate the data present • Multi-Line Comments
in the database. • The Multi-line comments start with /* and end
with */. So, any text mentioned between /* and
• Data Control Language(DCL) – */ will be ignored by the compiler.
Consists of commands which deal • Example:
with the user permissions and • /*Select all the columns
controls of the database system. • of all the records
• Transaction Control Language(TCL) – • from the Employee_Info table:*/
Consist of commands which deal • SELECT * FROM Students;
with the transaction of the database.
Data Definition Language (DDL)
• DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
• All the command of DDL are auto-committed that means it permanently save all the changes in the
database.
• Here are some commands that come under DDL:
• CREATE
• ALTER
• DROP
• TRUNCATE
• TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
• TRUNCATE TABLE table_name;  
• TRUNCATE TABLE EMPLOYEE;  
• DROP: It is used to delete both the structure and record stored in the table.
• DROP TABLE table_name;  
• DROP TABLE EMPLOYEE;  
Data Definition Language (DDL)
• CREATE It is used to create a new table in the database.
• CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);  
• CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DA
TE);  
• You can also create a table using another table.
• Syntax:
• Example:
• CREATE TABLE NewTableName AS
• CREATE TABLE ExampleTable AS
• SELECT Column1, column2,..., ColumnN
• SELECT Emp_Name, Phone_Num
• FROM ExistingTableName
• FROM Employee_Info;
• WHERE ....;
Data Definition Language (DDL)
• ALTER: It is used to alter the structure of the database. This change could be either to modify
the characteristics of an existing attribute or probably to add a new attribute.
• ALTER TABLE table_name ADD column_name COLUMN-definition;    
• ALTER TABLE table_name MODIFY(column_definitions....);  
1.ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));  
2.ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));  
• SQL Commands: Constraints Used In Database
• Constraints are used in a database to specify the rules for data in a table. The following
are the different types of constraints:
• NOT NULL :This constraint ensures that a column cannot have a NULL value.
• UNIQUE: This constraint ensures that all the values in a column are unique.
• CHECK: This constraint ensures that all the values in a column satisfy a specific condition.
• DEFAULT: This constraint consists of a set of default values for a column when no value is
specified.
• --UNIQUE on Create Table
Data Definition Language (DDL)
• CREATE TABLE Employee_Info
• --NOT NULL on Create Table
• CREATE TABLE Employee_Info •(
•( • EmployeeID int NOT NULL UNIQUE,
• EmployeeID int NOT NULL, • EmployeeName varchar(255) NOT NULL,
• EmployeeName varchar(255) NOT NULL, • Emergency ContactName varchar(255),
• Emergency ContactName varchar(255), • PhoneNumber int NOT NULL,
• PhoneNumber int NOT NULL,
• Address varchar(255),
• Address varchar(255),
• City varchar(255),
• City varchar(255),
• Country varchar(255) • Country varchar(255)
• ); • );
• --NOT NULL on ALTER TABLE • --UNIQUE on ALTER TABLE
• ALTER TABLE Employee_Info • ALTER TABLE Employee_Info
• MODIFY PhoneNumber int NOT NULL; • ADD UNIQUE (Employee_ID);
Data Definition Language (DDL) • --DEFAULT Constraint on CREATE TABLE
• --CHECK Constraint on CREATE TABLE
• CREATE TABLE Employee_Info
• CREATE TABLE Employee_Info •(
•( • EmployeeID int NOT NULL,
• EmployeeID int NOT NULL, • EmployeeName varchar(255),
• EmployeeName varchar(255), • Emergency ContactName varchar(255),
• Emergency ContactName varchar(255), • PhoneNumber int,
• PhoneNumber int,
• Address varchar(255),
• Address varchar(255),
• City varchar(255),
• City varchar(255),
• Country varchar(255) DEFAULT 'India'
• Country varchar(255) CHECK (Country=='India')
• ); • );
• --CHECK Constraint on ALTER TABLE • --DEFAULT Constraint on ALTER TABLE
• ALTER TABLE Employee_Info • ALTER TABLE Employee_Info
• ADD CHECK (Country=='India'); • ADD CONSTRAINT defau_Country
• DEFAULT 'India' FOR Country;
Data Manipulation Language
• DML commands are used to modify the database. It is responsible for all form of changes in
the database.
• The command of DML is not auto-committed that means it can't permanently save all the
changes in the database. They can be rollback.
• INSERT
• UPDATE
• DELETE
• SELECT
• INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.
• INSERT INTO TABLE_NAME   (col1, col2, col3,.... col N)  VALUES (value1, value2, value3, .... v
alueN); 
•  INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);
• INSERT INTO book (Author, Subject) VALUES (“ABC", "DBMS");  
Data Manipulation Language
• UPDATE: This command is used to update or modify the value of a
column in the table.
• UPDATE table_name SET [column_name1= value1,...column_nameN = 
valueN] [WHERE CONDITION]   
• UPDATE students    SET User_Name = ’XYZ'    WHERE Student_Id = '3’  
• DELETE: It is used to remove one or more row from a table.
• DELETE FROM table_name [WHERE condition];  
• DELETE FROM book  WHERE Author=“ABC";  
• Example:
Data Manipulation Language
• SELECT EmployeeID, EmployeeName
• SELECT FROM Employee_Info;
• This statement is used to select data • --(*) is used to select all from the table
from a database and the data • SELECT * FROM Employee_Info;
returned is stored in a result table,
called the result-set. • -- To select the number of records to
return use:
• Syntax
• SELECT TOP 3 * FROM Employee_Info;
• SELECT Column1, Column2, ...ColumN
• you can use the following keywords with
• FROM TableName; the SELECT statement:
• --(*) is used to select all from the table • DISTINCT
• SELECT * FROM table_name; • ORDER BY
• -- To select the number of records to • GROUP BY
return use:
• HAVING Clause
• INTO
Data Manipulation Language• Example:
• The ‘SELECT DISTINCT’ Statement • -- Select all employees from the
• This statement is used to return only different 'Employee_Info' table sorted by
values. EmergencyContactName:
• Syntax:SELECT DISTINCT Column1, • SELECT * FROM Employee_Info
Column2, ...ColumnN
• FROM TableName;
• ORDER BY EmergencyContactName;
• Example SELECT DISTINCT PhoneNumber FROM • -- Select all employees from the
Employee_Info; 'Employee_Info' table sorted by
• The ‘ORDER BY’ Statement EmergencyContactName in
• The ‘ORDER BY’ statement is used to sort the Descending order:
required results in ascending or descending order.
The results are sorted in ascending order by default. • SELECT * FROM Employee_Info
• Syntax: SELECT Column1, Column2, ...ColumnN • ORDER BY EmergencyContactName
• FROM TableName DESC;
• ORDER BY Column1, Column2, ... ASC|DESC;
Examples
Data Manipulation Language • The ‘HAVING’ Clause
• The ‘HAVING’ clause is used in SQL because the
• The ‘GROUP BY’ Statement WHERE keyword cannot be used everywhere.
• This ‘GROUP BY’ statement is used with the • Syntax :SELECT ColumnName(s)
aggregate functions to group the result-set by one • FROM TableName
or more columns. • WHERE Condition
• Syntax :SELECT Column1, Column2,..., ColumnN • GROUP BY ColumnName(s)
• FROM TableName • HAVING Condition
• WHERE Condition • ORDER BY ColumnName(s);
• GROUP BY ColumnName(s) • Example
• /* To list the number of employees in each city.
• ORDER BY ColumnName(s);
The employees should be sorted high to low and
• Example only those cities must be included who have more
than 5 employees:*/
• -- To list the number of employees from each city.
• SELECT COUNT(EmployeeID), City
• SELECT COUNT(EmployeeID), City
• FROM Employee_Info
• FROM Employee_Info
• GROUP BY City
• GROUP BY City; • HAVING COUNT(EmployeeID) > 2
• ORDER BY COUNT(EmployeeID) DESC;
Examples
Aggregate Functions
• Example
• An aggregate function in SQL performs a
calculation on multiple values and returns a • SELECT MIN(EmployeeID) AS SmallestID
single value. • FROM Employee_Info;
• SQL provides many aggregate functions that • MAX() Function
include avg, count, sum, min, max, etc.
• The MAX function returns the largest
• An aggregate function ignores NULL values value of the selected column in a table.
when it performs the calculation, except for
the count function. • Syntax
• MIN() Function • SELECT MAX(ColumnName)
• The MIN function returns the smallest value of • FROM TableName
the selected column in a table. • WHERE Condition;
• Syntax • Example
• SELECT MIN(ColumnName) • SELECT MAX(Salary) AS LargestFees
• FROM TableName • FROM Employee_Salary;
• WHERE Condition;
Aggregate Functions • Example
• SELECT SUM(Salary)
• COUNT() Function
• FROM Employee_Salary;
• The COUNT function returns the number of
rows which match the specified criteria. • AVG() Function
• Syntax: SELECT COUNT(ColumnName) FROM • The AVG function returns the
TableName average value of a numeric column
• WHERE Condition; that you choose.
• Example • Syntax SELECT AVG(ColumnName)
• SELECT COUNT(EmployeeID) • FROM TableName WHERE
• FROM Employee_Info; Condition;
• SUM() Function • Example
• The SUM function returns the total sum of a
numeric column that you choose.
• SELECT AVG(Salary) FROM
Employee_Salary;
• Syntax: SELECT SUM(ColumnName) FROM
TableName WHERE Condition;
Group by -aggregate example
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:
1.UNION: It is used to combine two or more result sets into a single set, without duplicates.
2.UNION ALL: It is used to combine two or more result sets into a single set, including
duplicates.
3.INTERSECT: It is used to combine two result sets and returns the data which are common in
both the result set.
4.EXCEPT/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:
1.Every SELECT statement involved in the query must have a similar number of columns.
2.The columns in the SELECT statement must be in the same order and have similar data types.
3.In 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
• Examples to understand SET Operators in MySQL: We are going to use EmployeeUK and
EmployeeUSA tables to understand the SET Operators in MySQL.
•CREATE DATABASE EmployeeDB; •CREATE TABLE EmployeeUSA
•USE EmployeeDB; •(
• CREATE TABLE EmployeeUK
•(
• EmployeeId INT PRIMARY KEY,
• EmployeeId INT PRIMARY KEY, • FirstName VARCHAR(50),
• FirstName VARCHAR(50), • LastName VARCHAR(50),
• LastName VARCHAR(50), • Gender VARCHAR(10),
• Gender VARCHAR(10), • Department VARCHAR(20)
• Department VARCHAR(20)
•);
•); • INSERT INTO EmployeeUSA VALUES(1, 'James', 'Pattrick', 'Male','IT');
• INSERT INTO EmployeeUK VALUES(1, 'Pranaya', 'Rout', 'Male','IT');
•INSERT INTO EmployeeUSA VALUES(2, 'Priyanka', 'Dewangan', 'Female','IT');
•INSERT INTO EmployeeUK VALUES(2, 'Priyanka', 'Dewangan', 'Female','IT');
•INSERT INTO EmployeeUSA VALUES(3, 'Sara', 'Taylor', 'Female','HR');
•INSERT INTO EmployeeUK VALUES(3, 'Preety', 'Tiwary', 'Female','HR');
•INSERT INTO EmployeeUK VALUES(4, 'Subrat', 'Sahoo', 'Male','HR'); •INSERT INTO EmployeeUSA VALUES(4, 'Subrat', 'Sahoo', 'Male','HR');
•INSERT INTO EmployeeUK VALUES(5, 'Anurag', 'Mohanty', 'Male','IT'); •INSERT INTO EmployeeUSA VALUES(5, 'Sushanta', 'Jena', 'Male','HR');
•INSERT INTO EmployeeUK VALUES(6, 'Rajesh', 'Pradhan', 'Male','HR'); •INSERT INTO EmployeeUSA VALUES(6, 'Mahesh', 'Sindhey', 'Female','HR');
•INSERT INTO EmployeeUK VALUES(7, 'Hina', 'Sharma', 'Female','IT'); •INSERT INTO EmployeeUSA VALUES(7, 'Hina', 'Sharma', 'Female','IT');
SQL Commands: Set Operations • UNION ALL Operator in MySQL
• UNION Operator in MySQL
• The UNION ALL operator is used to
• The UNION operator is used to combine
the result set of two or more SELECT
combine the result set of two or more
statements into a single result set by SELECT statements into a single result
removing the duplicate records. That including the duplicate values. 
means the UNION Operator selects only
the distinct values.

• SELECT FirstName, LastName, Gender,


• SELECT FirstName, LastName, Gender, Department FROM EmployeeUK
Department FROM EmployeeUK
• UNION
• UNION ALL
• SELECT FirstName, LastName, Gender, • SELECT FirstName, LastName, Gender,
Department FROM EmployeeUSA; Department FROM EmployeeUSA;
• Here we don’t have any duplicate data. • Here we got all the 14 rows in the
Here, in the result set, we got a total of
11 rows out of 14 rows. This is because 3 result set.
rows are present in both the result set.
SQL Commands: Set Operations • MySQL EXCEPT Operator:
• INTERSECT Operator in MySQL • The EXCEPT operator is used to combine two
• The INTERSECT operator is used to combine two result sets tables or two result sets and will return rows from
and returns the data which are common in both the result
set.
the first select statement that are not present in
the second select statement.

• But the INTERSECT Operator is not supported by MYSQL. We


can achieve the INTERSECT Operator functionality in MySQL • But, the EXCEPT Operator is not supported by
using the following ways. MYSQL. We can achieve the EXCEPT Operator
• Using IN Operator to achieve INTERSECT functionality: functionality in MySQL using the following ways.
• Here, we are checking the FirstName column value only.
Following is the SQL Query using the IN Operator which
• Using NOT IN Operator to achieve EXCEPT
returns the common employees i.e. the employees which functionality:
are present in both t EmployeeUK and EmployeeUSA tables. • Here, we are checking the FirstName column
Here, we are checking common based on the First Name
column value. value only. Following is the SQL Query using the
• SELECT * FROM EmployeeUK NOT IN Operator which returns the employees
• WHERE FirstName IN (SELECT FirstName FROM from the first EmployeeUK table that are not
EmployeeUSA); present in the EmployeeUSA table.
Date Functions in SQL
• CURRENT_TIMESTAMP() Function
• CURRENT_TIMESTAMP() function returns the current system timestamp.
• SELECT CURRENT_TIMESTAMP AS CurrentServerDateTime;
• DATE_ADD() Function
• DATE_ADD() function adds a number to a datepart and returns the modified
datetime value. The following example adds 1 day to the specified date
• SELECT DATE_ADD('2022/10/01',interval 1 day) AS Result; -- 2022-10-02
• DATEDIFF(expr1,expr2)
• DATEDIFF() returns expr1 − expr2 expressed as a value in days from one date
to the other. expr1 and expr2 are date or date-and-time expressions.
• SELECT DATEDIFF('2022/10/01','2022/09/25’); --6
String Functions in SQL
• ASCII(str): Returns the numeric value of the leftmost character of the string str.
Returns 0 if str is the empty string. Returns NULL if str is NULL. ASCII() works for 8-
bit characters.
• SELECT ASCII('A’); --65
• INSERT(str,pos,len,newstr) :Returns the string str, with the substring beginning at
position pos and len characters long replaced by the string newstr.
• SELECT INSERT('Quadratic', 3, 4, 'What’); ---QuWhattic
• INSTR(str,substr) : Returns the position of the first occurrence of substring substr
in string str.
• SELECT INSTR('foobarbar', 'bar’); -- 4
• select LCASE('CoLleGe’); ---- college
• select Length('vit’); --3
Nested queries in SQL

• 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.

2 It authorizes access preferences to It withdraws access preferences to users.


users.
3 In the GRANT command, you need to In the REVOKE command, if the access for one
define the permissions for each user. user is withdrawn, then all the permissions
provided by that particular person to others will
also be removed.
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: 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;  
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;
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 ;

mysql> CALL viewEmployees();


Create Procedure Example
Display all records of studentinfo table whose
marks are greater than 70 

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');

• How to Create a View in MySQL?


• CREATE VIEW vwEmployee AS SELECT * FROM
Employee;
Data Query Language

• DQL is used to fetch the data from the database.


• It uses only one command:
• SELECT
• SELECT: This is the same as the projection operation of relational algebra. It is
used to select the attribute based on the condition described by WHERE clause.
Syntax: SELECT expressions     SELECT emp_name
FROM TABLES     FROM employee
WHERE conditions;   WHERE age > 20;

You might also like