SQL For Data Science
SQL For Data Science
Training Centre
Content:
● Introduc on to Database
● Introduc on to SQL (Structured Query Language)
● SQL Commands : DDL, DML, DCL, TCL, DQL
● DDL (Data De ni on Language)
1. CREATE
2. ALTER
3. TRUNCATE
4. DROP
● DML (Data Manipula on language) + DQL (Data Query Language)
CRUD OPERATIONS
1. INSERT
2. SELECT
3. UPDATE
4. DELETE
● SQL CONSTRAINTS:
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
7. AUTO_INCREMENT
● SQL CLAUSES
1. WHERE:
OPERATORS IN SQL
2. DISTINCT
3. LIMIT
4. ORDER BY
5. GROUP BY
6. HAVING:
AGGREGATE FUNCTIONS IN SQL
7. UNION & UNION ALL
Velocity
Corporate Training Centre Pune.
ti
ti
fi
ti
ti
● SUBQUERIES
● SQL JOINS
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
● ANALYTICAL FUNCTIONS
1. ROW_NUMBER ()
2. LEAD ()
3. LAG ()
4. RANK
5. DENSE_RANK ()
DATABASE:
• A database is an organized collec on of data, stored in a computer system.
• It is an electronic system that makes data access, manipula on, retrieval, storage, and
management very easy.
DBMS:
DBMS is the set of applica on program used to access, update and manage the data.
The goal of DBMS is to provide an environment that is both convenient and e cient to use
for :
• Storing data into the database.
• Retrieving data from the database
RDBMS:
• It is a database management system based on a rela onal model. It facilitates you to store,
access, and manipulate the data stored in rela onal databases.
• Rela onal database stores the data in the collec on of tables.
• Examples of rela onal database management systems are MySQL, SQL Server, Oracle,
PostgreSQL, etc.
DATABASE TABLES:
Data in rela onal databases is stored in the form of tables. A database o en contains one or
mul ple tables. Each table is de ned with a unique name and contains rows and columns.
The table above contains 5 rows/records (one for each employee) and 4 columns (emp_id,
emp_name, salary, loca on ).
ti
ti
ti
ti
ti
ti
fi
ti
ti
ti
ti
ti
ft
ffi
1. Single-line comment
We can comment one line at the me using “--” before the text you want to comment out.
Syntax: -- text_of_comment
ti
ti
ti
ff
ti
fi
tt
ti
ti
SQL COMMANDS:
SQL commands are instruc ons. these are used to communicate with the database and
perform CRUD opera ons (Create, Read, Update, Delete).
SQL Description
CREATE Creates a database and database objects like tables and views
fi
fi
fi
fi
ti
ti
ti
ti
ti
ti
ti
These commands are used to grant or revoke database access. Only database administrators
have the access to perform these ac vi es.
DCL Commands : GRANT, REVOKE
These commands are used to manage a database transac on. A transac on is a group of
tasks that can have mul ple INSERTs, DELETEs, and UPDATEs.
TCL Commands : COMMIT, ROLLBACK, SAVEPOINT
1.1. CREATE:
Create command is used to create database, and database objects like tables and views.
To start using this database created above, we need to use below syntax:
Syntax:
USE database_name;
Example:
USE db_dev;
ti
ti
ti
ti
ti
ti
CREATE TABLE statement is used to create a table with its de ned structure.
CREATE TABLE Table_name
(
Column1 datatype,
Column2 datatype,
…);
The column parameter speci es the name of the columns/ elds in the table.
The datatype parameter speci es the type of data a column can hold (e.g. varchar, char, int,
date, etc)
Example:
The following example creates an employee table that contains four columns emp_id,
emp_name, salary & loca on.
To check the structure of any database table, we can use DESC command.
DESC stands for describe. This basically gives the structural details of an exis ng table
Syntax:
DESC Table_name;
ti
ti
fi
fi
fi
fi
ti
Output:
FIELD TYPE NULL KEY DEFAULT EXTRA
Emp_id Int YES NULL
Example:
SHOW CREATE TABLE employee;
Output:
CREATE TABLE `employee` (
`emp_id` int DEFAULT NULL,
`emp_name` varchar(10) DEFAULT NULL,
`salary` int DEFAULT NULL,
`loca on` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=u 8mb4 COLLATE=u 8mb4_0900_ai_ci
1.2. ALTER:
fi
ti
ti
fi
ti
tf
ti
ti
ti
tf
Syntax: To add column as the rst column of the table, use below syntax
ALTER TABLE table_name ADD COLUMN column_name datatype FIRST;
1.3. TRUNCATE:
The TRUNCATE statement can be used to DELETE all rows from table/empty the table.
Syntax:
TRUNCATE TABLE table_name;
ti
ft
fi
fi
ti
1.4. DROP:
Syntax:
DROP DATABASE database_name;
CREATE INSERT
Insert data into database
DATA INTO
2.1. INSERT:
2.1.1. Specify both the column names and the values to be inserted:
Syntax:
INSERT INTO table_name (column1, column2, column3,…) values(value1,
value2, value3,…);
ti
ti
ti
ff
Example:
INSERT INTO employee
(emp_id, emp_name, salary, loca on)
VALUES
(1001, 'Aditya', 50000,'Mumbai');
2.1.2. You do not need to specify the column names in the SQL query If you are adding
values for all the columns of the table,
however, make sure the order of the values is in the same order as the
columns in the table.
Syntax:
INSERT INTO table_name values(value1, value2, value3,…);
Example:
INSERT INTO employee
VALUES
(1002,'Rahul', 45000,'Pune');
2.1.3. We can also insert mul ple records using a single INSERT INTO query.
Syntax:
INSERT INTO table_name
(column1, column2, column3,…)
values(value1, value2, value3,…)
(value1, value2, value3,…);
Example :
INSERT INTO employee (emp_id, emp_name, salary, loca on)
VALUES
(1003,'Rohit',40000,NULL),
(1004,'Saurav',60000,'Chennai'),
(1005,'Manish',30000,'Mumbai');
2.2. SELECT:
SELECT command is used to read data from database.
ti
ti
ti
Syntax:
SELECT * FROM table_name;
Example:
SELECT * FROM employee;
Output:
Emp_id emp_name Salary Location
1001 Aditya 50000 Mumbai
FROM clause is used to specify a data source, which can either be a table, view or a
subquery.
Example:
fi
2.3. UPDATE:
The UPDATE statement is used to modify the exis ng data from a table.
Syntax:
UPDATE table_name
SET column_name1=new_value,
column_name2=new_value;
Example:
The following SQL query update the employee table with a new Loca on for all rows.
UPDATE employee SET loca on = Benguluru;
Table A er update:
Emp_id emp_name Salary Location
1001 Aditya 50000 Benguluru
ft
ti
ti
ti
CASE Statement:
The CASE statement goes through condi ons and return a value when the rst condi on is
met (like an IF-THEN-ELSE statement). So, once a condi on is true, it will stop reading and
return the result.
• If no condi ons are true, it will return the value in the ELSE clause.
• If there is no ELSE part and no condi ons are true, it returns NULL.
• Else, will have the original column value.Syntax:
UPDATE table_name SET column_name=
CASE column_name
WHEN condi on THEN result1
WHEN condi on THEN result2
ELSE result
END;
Example:
The following SQL query update the employee table with a di erent Loca on for all rows
based on a condi on.
The rows which does not sa sfy any of these condi ons, will have original loca on value.
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ff
ti
fi
ti
ti
Table a er update:
Emp_id emp_name Salary Location
1001
Aditya 50000 Chennai
2.4. DELETE:
Syntax:
DELETE FROM table_name;
Example:
The following DELETE statement will delete all rows from an employee table.
Table a er delete:
Emp_id emp_name Salary Location
ft
ft
CONSTRAINTS:
SQL constraints are used to specify rules for the data in a table.
• SQL constraints are used to limit the type of data that can go into a table.
• This ensures the accuracy and reliability of the data in the table.
• If there is any viola on between the constraint and the data ac on, the ac on is aborted.
Constraint Description
NOT NULL Ensures that a NULL value can not be stored in a column
UNIQUE This constraint makes sure that all the values in a column are di erent
CHECK This constraint ensures that all the values in a column satisfy a speci c
condition
DAFAULT This constraint consists of default value for a column when no value is
speci ed
PRIMARY Ensures that the column value in every row is unique and has no null
KEY value
1. NOT NULL
The NOT NULL constraint enforces a column to NOT accept NULL values.
Syntax:
CREATE TABLE Table_name
(
Column1 datatype NOT NULL,
Column2 datatype NOT NULL,
Column3 datatype,
…);
The following SQL ensures that the roll_no and address column will NOT accept NULL values
when the "Student" table is created:
fi
ti
ti
ff
fi
ti
Example:
CREATE TABLE student
(
roll_no int NOT NULL,
stud_name varchar(20),
address varchar(25) NOT NULL );
To apply NOT NULL constraint on an exis ng database table, use below syntax
Syntax:
ALTER TABLE table_name MODIFY COLUMN column_name data_type NOT
NULL;
Example:
Below query is used to add a NOT NULL constraint on emp_id column of employee table:
Example:
2. UNIQUE KEY
• The UNIQUE KEY constraint ensures that all values in a column are dis nct.
• UNIQUE Constraint allows NULL values.
• Each table can have mul ple UNIQUE Constraints.
Syntax:
CREATE TABLE table_name (
column1 datatype UNIQUE,
Column2 datatype UNIQUE,
Column3 datatype);
ti
ti
ti
The following SQL ensures that the roll_no column will not accept duplicate values when the
"Student" table is created:
Example:
CREATE TABLE student (
roll_no int UNIQUE,
stud_name varchar(20),
address varchar(25));
To apply UNIQUE KEY constraint on an exis ng database table, use below syntax.
Syntax:
ALTER TABLE table_name MODIFY COLUMN column_name data_type
UNIQUE;
Example:
Below query is used to add a UNIQUE KEY constraint on emp_id column of employee table:
Example:
ALTER TABLE employee DROP INDEX emp_id;
3. PRIMARY KEY
• The PRIMARY KEY constraint is a combina on of a NOT NULL and UNIQUE.
• PRIMARY KEY uniquely iden es each row in a table
• Primary keys must contain UNIQUE values, and cannot have NULL values.
A table can have only ONE PRIMARY KEY but a single primary key can contain one or
mul ple columns
ti
ti
fi
ti
ti
Syntax:
CREATE TABLE table_name
(
column1 datatype PRIMARY KEY,
column2 datatype,
column3 datatype,
…);
Example:
CREATE TABLE student
(roll_no int PRIMARY KEY,
stud_name varchar(20),
address varchar(25));
We can apply a PRIMARY KEY constraint on an exis ng database table using below syntax:
ALTER TABLE employee MODIFY COLUMN Column_name Data_type
PRIMARY KEY;
Example:
ALTER TABLE employee MODIFY COLUMN emp_id int PRIMARY KEY;
Example:
ALTER TABLE employee DROP PRIMARY KEY;
ti
4. FOREIGN KEY
• A FOREIGN KEY is a eld in one table, that refers to the PRIMARY KEY in another table.
• It is used to de ne a rela on between two or mul ple database tables.
• We can have more than one FOREIGN KEYs in a table .
• The table with the FOREIGN KEY is called the child or referencing table, and the
table with the PRIMARY KEY is called the parent or referenced table.
Relationship
Foreign Key
Primary Key
Syntax:
CREATE TABLE child_table_name
(column1 datatype,
column2 datatype,
column3 datatype,
FOREIGN KEY (column_of_child_table) references
parent_table(parent_table_primary_key)
ON DELETE CASCADE,
ON UPDATE CASCADE
);
Example:
Below query can be used to de ne roll_no as the FOREIGN KEY in course table which refers
to the PRIMARY KEY of student table we have used above.
fi
fi
ti
fi
ti
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, as it has to be one of the values contained in the parent table.
We can apply a FOREIGN KEY constraint on an exis ng database table using below syntax:
Here, we can get the name of foreign key from create table statement .
To get the create table statement, use below syntax:
SHOW create table table_name;
5. CHECK
• The CHECK constraint is used to limit the value range that can be placed in a column.
If you de ne a CHECK constraint on a column it will allow only certain values for this
column.
fi
ti
fi
fi
ti
ti
Syntax:
CREATE TABLE table_name (column1 datatype, column2 datatype,
CHECK(Condi on));
Example:
Below query will create a table that will restrict the roll_no column to have values > 100.
We can apply a Check constraint on an exis ng database table using below syntax:
ALTER TABLE Table_name MODIFY COLUMN Column_name data_type
CHECK(condi on);
Here, we can get the name of constraint from create table statement .
6. DEFAULT
• The DEFAULT constraint is used to set a default value to a column.
• The default value will be added to all new records, if no other value is speci ed.
Syntax:
CREATE TABLE table_name
(column1 datatype DEFAULT value,
column2 datatype,
column3 datatype);
Example:
Below query can be used to set a default value for address column as pune in student table
ti
ti
ti
fi
We can apply a DEFAULT constraint on an exis ng database table using below syntax:
ALTER TABLE table_name MODIFY COLUMN column_name data_type
DEFAULT value;
7. AUTO_INCREMENT:
• The AUTO_INCREMENT a ribute can be used to generate a unique iden ty for new rows.
• It is mandatory to de ne a column as key to auto_increment it .
Syntax:
CREATE TABLE table_name (column1 datatype primary key
Auto_increment, column2 datatype, column3 datatype);
Example:
Below query can be used to apply auto_increment on roll_no column of Student table
fi
tt
ti
ti
SQL CLAUSES:
The sequence of execu on of sql clauses
1. WHERE:
WHERE clause can be used with SELECT statement to read par cular rows sa sfying the
lter condi on
Syntax:
SELECT * FROM table_name where condi on;
Example:
Below statement can be used to read details about an employee with emp_id=1001.
Output:
Emp_id emp_name Salary Location
1001 Aditya 50000 Mumbai
fi
ti
ti
ti
fi
ff
ti
fi
ti
fi
ti
WHERE clause can be used with UPDATE statement to UPDATE only records sa sfying a lter
condi on.
Syntax:
UPDATE table_name SET column_name=new_value where condi on;
Example:
Below statement will UPDATE the loca on value where it is NULL:
Table a er update:
ti
ft
ti
ti
ti
ti
ti
fi
WHERE clause can be used with DELETE statement to DELETE only speci c records.
Syntax:
DELETE FROM table_name where condi on;
Table a er delete:
Emp_id emp_name Salary Location
1001 Aditya 50000 Mumbai
ff
ft
fi
ti
ti
fi
ti
• OPERATORS IN SQL:
WHERE clause can be combined with the below operators to fetch the required result in SQL
Operator Descrip on
= Equal To
!= Not Equal To
1. OR and AND
The AND and OR operators are used to lter records based on more than one condi on:
• The AND operator displays a record if all the condi ons separated by AND are TRUE.
• The OR operator displays a record if any of the condi ons separated by OR is TRUE.
1.1. OR
It is a SQL statement used to access records which sa s es either condi on combined using
OR.
Syntax:
SELECT column1, column2 from table_name where Condi on1 OR
Condi on 2;
ti
ti
ti
tt
tt
ti
ti
ti
ti
fi
ti
ti
ti
fi
ti
ti
ti
Example:
The following SQL statement selects all elds from employee where emp_id=1001 or
emp_name = Saurav
Output:
Emp_id emp_name Salary Location
1001 Aditya 50000 Mumbai
1.2. AND
Example :
Output :
Emp_id emp_name Salary Location
1001 Aditya 50000 Mumbai
2. LIKE
• The LIKE operator is used in a WHERE clause to search for a speci ed pa ern in a column.
• There are two wildcards o en used with the LIKE operator:
The percent sign (%) represents zero, one, or mul ple characters
The underscore sign (_) represents one, single character
Syntax:
SELECT * FROM table_name WHERE column LIKE pa ern;
ti
ft
fi
ti
ti
fi
tt
fi
ti
ti
tt
Output :
Emp_id emp_name Salary Location
1002 Rahul 45000 Pune
Example 2: SELECT all records WHERE the value of the emp_name column does NOT start
with the le er "A".
Syntax :
SELECT * FROM table_name WHERE column NOT LIKE pa ern;
Output :
Emp_id emp_name Salary Location
1002 Rahul 45000 Pune
tt
tt
Example4: select all records where the value of the column starts with le er ‘a’ and ends
with the le er ‘a'
Example:
Output :
Emp_id emp_name Salary Location
1001 Aditya 50000 Mumbai
Example 5: SELECT all records where the emp_name contains the le er "a".
Output:
Emp_id emp_name Salary Location
1001 Aditya 50000 mumbai
3. IN and NOT IN
These operators allows you to specify one or mul ple values in a WHERE clause.
Syntax:
SELECT * FROM table_name
WHERE Column IN/NOT IN (Value1, Value2, Value3...)
Example1 :
The following SQL statement selects all rows where emp_name is in "Rohit", “Saurav":
tt
ti
tt
tt
Output:
Emp_id emp_name Salary Location
1003 Rohit 40000 NULL
Example2:
The following SQL statement selects all employees except "Rohit", "Saurav":
Example :
Output:
Emp_id emp_name Salary Location
1001 Aditya 50000 Mumbai
4. BETWEEN
• The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.
• Here, start and end values are included in the output.
Syntax :
SELECT * FROM table_name WHERE Column_name BETWEEN Value1 AND
Value2;
Example :
Output:
Emp_id emp_name Salary Location
1001 Aditya 50000 Mumbai
To display the records outside the given range , use NOT BETWEEN:
Syntax :
SELECT * FROM table_name WHERE Column_name NOT BETWEEN Value1
AND Value2;
Example :
SELECT * FROM employee WHERE salary NOT BETWEEN 40000 AND 50000;
Output :
Emp_id emp_name Salary Location
1004 Saurav 60000 Chennai
2. DISTINCT :
DISTINCT clause is used to fetch the UNIQUE values from a column of a table.
Syntax:
SELECT DISTINCT column_name FROM table_name;
Example: Below query can be used to fetch UNIQUE loca on values FROM employee table
ti
ti
Output:
Location
Mumbai
Pune
NULL
Chennai
3. LIMIT:
LIMIT clause is used to limit the number of records to return.
Syntax:
SELECT * FROM table_name LIMIT OFFSET, NUMBER OF ROWS
Here,
OFFSET parameter speci es the number of rows to skip from top.
NUMBER OF ROWS parameter speci es the number of rows to read.
Example:
Below statement will skip 2 rows from top and return next 2 rows in the output.
Output:
Emp_id emp_name Salary Location
1003 Rohit 40000 NULL
fi
fi
Here, when we pass only one parameter to limit clause, it is the number of rows to read.
OFFSET value becomes 0 in this case. This statement will read top 2 rows from a table
Output:
Emp_id emp_name Salary Location
1001 Aditya 50000 Mumbai
4. ORDER BY :
• ORDER BY clause is used to sort the data in an ascending or descending order.
• The ORDER BY keyword sorts the records in ascending order by default.
• To sort the records in descending order, use the DESC keyword.
Syntax:
SELECT * FROM table_name ORDER BY column1, column2;
Example: Below statement will sort the data of employee table in ascending order of
emp_name:
Output:
Emp_id emp_name Salary Location
Below statement will sort the data of employee table in descending order of emp_name:
ALIAS :
• SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are
o en used to make column names more readable.
• An alias only exists for the dura on of that query. An alias is created with the AS keyword.
Example:
The following SQL statement creates two aliases, one for the calculated column and one for
the table:
SELECT emp_id, emp_name, salary, 0.25*salary as per_salary FROM employee as e;
Output:
Emp_id emp_name Salary per_salary
1001 Aditya 50000 12500.00
ft
ti
• AGGREGATE FUNCTIONS:
• An aggregate func on performs calcula ons on a set of values and returns a single value.
Syntax:
SELECT MIN(column name),MAX(column name),SUM(column
name),AVG(column name) FROM table_name;
Example:
5. COUNT():
• Returns total number of records when used with * or any constant number
• Returns total number of Non-Null Values of a column when used with a speci c column
Syntax:
SELECT COUNT(*) FROM Table_name;
SELECT COUNT(1) FROM Table_name;
SELECT COUNT(column_name) FROM table_name;
Example:
ti
ti
ti
fi
5. GROUP BY :
• The GROUP BY statement groups rows that have same values into summary rows.
• The GROUP BY statement is o en used with aggregate func ons like (COUNT(), MAX(),
MIN(), SUM(), AVG()
• It returns a single row for each group
Syntax:
SELECT
Column,
AGGREGATE FUNCTION(Column)
FROM table_name
WHERE condi on
GROUP BY Column;
Example: Below query will create groups based on loca on values and will calculate the
number of employee, sum of salary, avg of salary for each group
6. HAVING :
• The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate func ons.
• It is used with group by and aggregate func ons to lter out grouped data.
ti
ti
ti
ti
ft
ti
fi
ti
ti
Syntax :
SELECT
Column,
AGGREGATE FUNCTION(Column)
FROM table_name
WHERE condi on
GROUP BY Column
HAVING Condi on;
Example: Below query will fetch loca ons where employee count>1
Output:
Location Count(emp_id)
Mumbai 2
These are used to append the data from di erent SELECT statements.
• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order
Syntax:
ti
ti
ti
ti
ff
ti
Student table:
roll_no stud_name Address
Course table:
course_id course_name roll_no
20 java 106
20 java 107
Example: below statement will append the result of both select queries
SELECT roll_no FROM student
union all
SELECT roll_no FROM course;
Output:
roll_no
101
102
103
104
105
101
102
106
107
Output:
Roll_no
101
102
103
104
105
106
107
• SQL JOINS
• Joins are used to combine the data from two or more database tables
• Join is an SQL statement it is used to join two or more tables based on the column having
similar values in the tables being joined.
Types of JOINS
1. INNER JOIN
• The INNER JOIN keyword selects records that have matching values in both tables.
• Inner join is a SQL statement which is use to show records in columns which are related to
common values
Syntax :
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Output:
roll_no stud_name Address course_id course_name
Syntax:
SELECT column_name(s)
FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example :
SELECT student.roll_no, stud_name, address, course_id, course_name
FROM
student
LEFT JOIN
course
ON student.roll_no=course.roll_no;
Output:
roll_no stud_name Address Course_id Course_name
Syntax :
SELECT column_name(s)
FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example :
SELECT student.roll_no, stud_name, address, course_id, course_name
FROM
student
RIGHT JOIN
course
ON student.roll_no=course.roll_no;
ft
Output :
roll_no stud_name Address course_id course_name
• MySQL does not support FULL JOIN, so you have to combine RIGHT JOIN, UNION and LEFT
JOIN to get an equivalent.
Syntax :
SELECT column_name(s)
FROM table1 LEFT JOIN table2
ON table1.column_name = table2.column_name
UNION
SELECT column_name(s)
FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example :
select s.roll_no, stud_name, address, course_id, course_name
from student s
right join
course c
on s.roll_no=c.roll_no
union
select s.roll_no, stud_name, address, course_id, course_name
from student s
le join
course c
on s.roll_no=c.roll_no;
Output :
Roll_no stud_name Address course_id course_name
101 Snehal pune 10 data science
ft
SUBQUERIES:
A Subquery is an inner query that is placed within an outer SQL query using di erent SQL
clauses like WHERE and FROM.
Types of subqueries:
1. Scalar Subqueries: the type of subqueries where inner query returns only single value
Syntax:
SELECT * FROM table_name WHERE col_name=(inner query)
Example:
Below query will fetch the details of an employee having max salary
Output:
Emp_id emp_name Salary Location
1004 Saurav 60000 Chennai
Example: Fetch the name and salary of an employee having salary equal to avg salary
SELECT emp_id, emp_name, salary, sal
FROM employee e
Inner join
(SELECT avg(salary) as sal from employee ) as avg_sal
On e.salary=avg_sal.sal;
ti
ff
ti
Here, AVG_SAL is the alias given to the derived table or an inner query. It is mandatory when
we use query in a from clause.
Output:
Emp_id emp_name Salary Sal
1002 Rahul 45000 45000.0000
2. Mul -row subquery : The type of subquery where inner query returns more than one
value
Syntax:
SELECT * FROM table_name WHERE column_name IN/NOT IN (inner query)
Example: 1. Fetch roll_no from student which are not present in course table
SELECT roll_no, stud_name, address
FROM student s
where roll_no NOT IN (
SELECT dis nct roll_no from course) ;
Output:
roll_no stud_name Address
ti
ti
ANALYTICAL FUNCTIONS:
• A window func on performs a calcula on across a set of table rows that are somehow
related to the current row.
• This is comparable to the type of calcula on that can be done with an aggregate func on.
But unlike regular aggregate func ons, use of a window func on does not cause rows to
become grouped into a single output row — the rows retain their separate iden es.
ti
ti
ti
ti
ti
ti
ti
ti
1. ROW_NUMBER():
It is an analy cal func on used to return a sequen al number to each row of the par on
OVER: It is an helping clause used with window func ons to de ne par on and sort order
PARTITION_BY: Used to divide data into par ons and perform computa on on each subset of
par oned data.
ORDER BY: Used to sort the data within de ned par on
Syntax:
SELECT column,
ROW_NUMBER() OVER
(PARTITION BY column name
ORDER BY column name
) FROM table_name;
Example: Display oldest 2 employees from each department(consider min emp_id is the
oldest emp)
select * from(
select *,
row_number() over (par on by dept_name order by emp_id) as rn from emp
) SQ
where rn<3;
Here,SQ is an alias which used for the inner query
rn is al alias used for the column calculated using row_number() func on.
Output:
Empid emp_name dept_name Salary Rn
101 Mohan Admin 4000 1
ti
ti
ti
ti
ti
ti
ti
fi
ti
ti
ti
ti
ti
fi
ti
ti
ti
ti
ti
ti
LEAD:
SELECT column,
LEAD(expression, o set, default_value) OVER
(PARTITION BY column name
ORDER BY column name
) FROM table_name;
LAG:
SELECT column,
LAG(expression, o set, default_value) OVER
(PARTITION BY column name
ORDER BY column name
) FROM table_name;
ff
ft
ff
ff
fi
Example :
SELECT *,
LEAD(salary,1,0) over () as next_sal,
LAG(salary,1,0) over () as prev_sal from emp;
Output:
Empid emp_name dept_name Salary next_sal prev_sal
101 Mohan Admin 4000 3000 0
DENSE_RANK : Rank of current row within its par on, without gaps
SELECT column,
DENSE_RANK() OVER
(PARTITION BY column name
ORDER BY column name
) FROM table_name;
Example :
SELECT emp_id, dept_name, salary,
rank() OVER (PARTITION BY dept_name ORDER BY salary DESC) as rnk
,dense_rank() OVER (PARTITION BY dept_name ORDER BY salary DESC) as dense_rnk
FROM emp;
Output:
emp_id dept_name Salary rnk dense_rnk
120 Admin 5000 1 1
ti
ti
ti
ti
ti
ti
119 HR 8000 1 1
107 HR 7000 2 2
117 HR 3500 3 3
102 HR 3000 4 4
105 HR 3000 4 4
114 HR 3000 4 4
112 IT 10000 1 1
111 IT 8000 2 2
110 IT 7000 3 3
109 IT 6500 4 4
115 IT 4500 5 5
103 IT 4000 6 6