0% found this document useful (0 votes)
5 views

SQL

This document serves as a comprehensive guide to SQL, covering fundamental concepts such as data types, primary and foreign keys, and constraints, as well as advanced topics like SQL joins, aggregate functions, and window functions. It includes practical examples and syntax for creating databases and tables, performing CRUD operations, and utilizing various SQL commands. The document is structured as a course, providing a step-by-step approach to learning SQL with notes and tutorials.

Uploaded by

Kartik Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

SQL

This document serves as a comprehensive guide to SQL, covering fundamental concepts such as data types, primary and foreign keys, and constraints, as well as advanced topics like SQL joins, aggregate functions, and window functions. It includes practical examples and syntax for creating databases and tables, performing CRUD operations, and utilizing various SQL commands. The document is structured as a course, providing a step-by-step approach to learning SQL with notes and tutorials.

Uploaded by

Kartik Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Complete SQL With Notes

1. Introduction to SQL-What Is SQL & Database


2. Data Types, Primary-Foreign Keys & Constraints
a. Install postgresql and pgadmin4
3. Create Table In SQL & Create Database

WELCOME, TO SQL COURSE


4. INSERT UPDATE, DELETE & ALTER Table
5. SELECT Statement & WHERE Clause with Example
6. How To Import Excel File (CSV) to SQL

STEP 7. Functions in SQL & String Function

BASIC BY
STEP
ADVANCE 8.
9.
Aggregate Functions – Types & Syntax
Group By and Having Clause
10. Time Stamp and Extract Function, Date Time Function
11. SQL JOINS – Types & Syntax
12. SELF JOIN, UNION & UNION ALL
13. Subquery
By Rishabh Mishra 14. Window Function – Types & Syntax
15. Case Statement/Expression with examples
16. CTE- Common Table Expression with examples
1 SQL By Rishabh Mishra 2

Introduction to SQL
WHAT IS SQL & DATABASE- • What is SQL
INTRODUCTION • It’s applications
• SQL v/s NoSQL
SQL Tutorial In Hindi-1 • Types of SQL Commands
• What is Database
• Excel v/s Database in SQL

SQL By Rishabh Mishra 3 SQL By Rishabh Mishra 4


What is SQL? SQL Application

SQL (Structured Query Language) is a


programming language used to interact
with database

CRUD is an acronym for CREATE, READ(SELECT),


UPDATE, and DELETE statements in SQL
SQL By Rishabh Mishra 5 SQL By Rishabh Mishra 6

SQL v/s NoSQL SQL Commands


Relational Database Non-Relational Database There are mainly 3 types of SQL commands:
SQL database NoSQL database • DDL (Data Definition Language): create, alter,
Data stored are either key-value pairs, and drop
Data stored in tables document-based, graph databases or wide-
column stores • DML (Data Manipulation Language): select,
These databases have fixed or static or
predefined schema
They have dynamic schema insert, update and delete
Low performance with huge volumes of data Easily work with huge volumes of data • DCL (Data Control Language): grant and revoke
Eg: PostgreSQL, MySQL, MS SQL Server Eg: MongoDB, Cassandra, Hbase
permission to users
SQL By Rishabh Mishra 7 SQL By Rishabh Mishra 8
What is Database? Excel v/s Database
Excel Database
Database is a system that allow users to Easy to use- untrained person can work Trained person can work

store and organise data Data stored less data Stores large amount of data

Good for one time analysis, quick charts Can automate tasks

No data integrity due to manual operation High data integrity

Low search/filter capabilities High search/filter capabilities

SQL By Rishabh Mishra 9 SQL By Rishabh Mishra 10

SQL Databases

DATA TYPES, PRIMARY &


FOREIGN KEYS, CONSTRAINTS
SQL Tutorial In Hindi-2

SQL By Rishabh Mishra 11 SQL By Rishabh Mishra 12


SQL Structure Database Diagram
Database
Columns Example
Tables
Data
Rows
(Rows & Columns) Example

RDBMS

SQL By Rishabh Mishra 13 SQL By Rishabh Mishra 14

Creating Database & Tables Data Types


• Data types
• Primary & Foreign keys • Data type of a column defines what value the
• Constraints column can store in table
• SQL Commands • Defined while creating tables in database
• CREATE
• Data types mainly classified into three categories +
• INSERT
• UPDATE
most used
• BACKUP oString: char, varchar, etc
• DELETE oNumeric: int, float, bool, etc
• ALTER oDate and time: date, datetime, etc
• DROP, TRUNCATE
SQL By Rishabh Mishra 15 SQL By Rishabh Mishra 16
Data Types Primary and Foreign Keys:
Commonly Used data types in SQL: Primary key (PK):
• int: used for the integer value • A Primary key is a unique column we set in a table to easily identify
• float: used to specify a decimal point number and locate data in queries
• bool: used to specify Boolean values true and false • A table can have only one primary key, which should be unique and
• char: fixed length string that can contain numbers, letters, and special NOT NULL
characters
Foreign keys (FK):
• varchar: variable length string that can contain numbers, letters, and
special characters • A Foreign key is a column used to link two or more tables together
• date: date format YYYY-MM-DD • A table can have any number of foreign keys, can contain duplicate
• datetime: date & time combination, format is YYYY-MM-DD hh:mm:ss and NULL values

SQL By Rishabh Mishra 17 SQL By Rishabh Mishra 18

Constraints Constraints
• Constraints are used to specify rules for data in a table Commonly used constraints in SQL:
• This ensures the accuracy and reliability of the data in the table • NOT NULL - Ensures that a column cannot have a NULL value
• Constraints can be specified when the table is created with the • UNIQUE - Ensures that all values in a column are different
CREATE TABLE statement, or • PRIMARY KEY - A combination of a NOT NULL and UNIQUE
• after the table is created with the ALTER TABLE statement • FOREIGN KEY - Prevents actions that would destroy links between
• Syntax tables (used to link multiple tables together)
CREATE TABLE table_name ( • CHECK - Ensures that the values in a column satisfies a specific
column1 datatype constraint, condition
column2 datatype constraint, • DEFAULT - Sets a default value for a column if no value is specified
column3 datatype constraint,
.... • CREATE INDEX - Used to create and retrieve data from the database
); very quickly
SQL By Rishabh Mishra 19 SQL By Rishabh Mishra 20
Install Postgre SQL Creating Database & Tables
(Click Here) SQL Tutorial In Hindi-3

SQL By Rishabh Mishra 21 SQL By Rishabh Mishra 22

Create Table
Insert, Update, Delete
The CREATE TABLE statement is used to create a new table in a database
• Syntax
CREATE TABLE table_name
(
column_name1 datatype constraint, Values in Table
+
column_name2 datatype constraint,
column_name3 datatype constraint,
);

• Example Alter, Drop & Truncate Table


CREATE TABLE customer
(
CustID int8 PRIMARY KEY,
CustName varchar(50) NOT NULL, SQL Tutorial In Hindi-4
Age int NOT NULL,
City char(50),
Salary numeric
);
SQL By Rishabh Mishra 23 SQL By Rishabh Mishra 24
Insert Values In Table Update Values In Table
The INSERT INTO statement is used to insert new records in a table The UPDATE command is used to update existing rows in a table
• Syntax • Syntax
INSERT INTO TABLE_NAME
(column1, column2, column3,...columnN)
UPDATE TABLE_NAME
VALUES SET “Column_name1” = ‘value1’, “Column_name2” = ‘value2’
(value1, value2, value3,...valueN); WHERE “ID” = ‘value’
• Example
INSERT INTO customer • Example
(CustID, CustName, Age, City, Salary)
UPDATE customer
VALUES
(1, 'Sam', 26, 'Delhi', 9000), SET CustName = 'Xam', Age= 32
(2, 'Ram', 19, 'Bangalore', 11000), WHERE CustID = 4;
(3, 'Pam', 31, 'Mumbai', 6000),
(4, 'Jam', 42, 'Pune', 10000);
SQL By Rishabh Mishra 25 SQL By Rishabh Mishra 26

ALTER Table ALTER Table Example


The ALTER TABLE statement is used to add, delete, or modify columns • ADD Column Syntax: Adding new ‘Gender’ column to customer table
in an existing table ALTER TABLE customer
• ALTER TABLE - ADD Column Syntax ADD COLUMN Gender varchar(10);
ALTER TABLE table_name
• ALTER/MODIFY COLUMN Syntax: changing Gender column data type
ADD COLUMN column_name ;
from varchar(10) to char(10)
• ALTER TABLE - DROP COLUMN Syntax ALTER TABLE customer
ALTER TABLE table_name ALTER COLUMN Gender char(10);
DROP COLUMN column_name;
• ALTER TABLE - ALTER/MODIFY COLUMN Syntax • DROP COLUMN Syntax: Deleting Gender column from customer table
ALTER TABLE table_name ALTER TABLE customer
ALTER COLUMN column_name datatype; DROP COLUMN Gender;

SQL By Rishabh Mishra 27 SQL By Rishabh Mishra 28


Delete Values In Table Drop & Truncate Table
The DELETE statement is used to delete existing records in a table The DROP TABLE command deletes a table in the database
• Syntax • Syntax
DELETE FROM table_name WHERE condition; DROP TABLE table_name;

• Example The TRUNCATE TABLE command deletes the data inside a table, but
DELETE FROM customer not the table itself
WHERE CustID = 3; • Syntax
TRUNCATE TABLE table_name;

SQL By Rishabh Mishra 29 SQL By Rishabh Mishra 30

Creating a Classroom dataset for practice


CREATE TABLE classroom
(
rollno int8 PRIMARY KEY,
name varchar(50) NOT NULL,

SELECT & WHERE CLAUSE


house char(12) NOT NULL,
grade char(1)
);

INSERT INTO classroom

SQL Tutorial In Hindi-5 (rollno, name, house, grade)


VALUES
(1, ‘Sam’, ‘Akash’, ‘B’),
(2, ‘Ram’, ‘Agni’, ‘A’),
(3, ‘Shyam’, ‘Jal’, ’B’),
(4, ‘Sundar’, ‘Agni’, ’A’),
(5, ‘Ram’, ‘Yayu’, ‘B’);

SQL By Rishabh Mishra 31 SQL By Rishabh Mishra 32


SELECT Statement WHERE Clause
The SELECT statement is used to select data from a database. The WHERE clause is used to filter records.
• Syntax It is used to extract only those records that fulfill a specified condition
SELECT column_name FROM table_name; • Syntax
SELECT column_name FROM table_name
To select all the fields available in the table WHERE conditions;
• Syntax
SELECT * FROM table_name; • Example
SELECT name FROM classroom
To select distinct/unique fields available in the table WHERE grade=‘A’;

• Syntax
SELECT DISTINCT Column_name FROM table_name;
SQL By Rishabh Mishra 33 SQL By Rishabh Mishra 34

Operators In SQL LIMIT Clause


The LIMIT clause is used to set an upper limit on the number of tuples returned by
The SQL reserved words and characters are called operators, which are SQL.
used with a WHERE clause in a SQL query
Example: below code will return 5 rows of data
Most used operators: SELECT column_name FROM table_name
1. Arithmetic operators : arithmetic operations on numeric values LIMIT 5;
Example: Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%)
2. Comparison operators: compare two different data of SQL table ORDER BY Clause
• Example: Equal (=), Not Equal (!=), Greater Than (>), Greater Than Equals to (>=)
The ORDER BY is used to sort the result-set in ascending (ASC) or descending
3. Logical operators: perform the Boolean operations order (DESC).
• Example: ALL, IN, BETWEEN, LIKE, AND, OR, NOT, ANY Example: below code will sort the output data by column name in ascending order
4. Bitwise operators: perform the bit operations on the Integer values SELECT column_name FROM table_name
• Example: Bitwise AND (&), Bitwise OR(|) ORDER BY column_name e ASC;
SQL By Rishabh Mishra 35 SQL By Rishabh Mishra 36
CSV files
• 👉 customer csv file:: https://bit.ly/3KLPb2P
• 👉 payment csv file:: https://bit.ly/41kIYjW

IMPORT CSV FILE


SQL Tutorial In Hindi-6

SQL By Rishabh Mishra 37 SQL By Rishabh Mishra 38

Functions In SQL
Functions in SQL are the database objects that contains a set
of SQL statements to perform a specific task. A function
accepts input parameters, perform actions, and then return
STRING FUNCTION the result.
Types of Function:
SQL Tutorial In Hindi-7 1. System Defined Function : these are built-in functions
• Example: rand(), round(), upper(), lower(), count(), sum(), avg(),
max(), etc
2. User-Defined Function : Once you define a function, you
can call it in the same way as the built-in functions
SQL By Rishabh Mishra 39 SQL By Rishabh Mishra 40
Most Used String Functions
String functions are used to perform an operation on input string and
return an output string
• UPPER() converts the value of a field to uppercase
• LOWER() converts the value of a field to lowercase
• LENGTH() returns the length of the value in a text field
AGGREGATE FUNCTION
• SUBSTRING() extracts a substring from a string
• NOW() returns the current system date and time SQL Tutorial In Hindi-8
• FORMAT() used to set the format of a field
• CONCAT() adds two or more strings together
• REPLACE() Replaces all occurrences of a substring within a string, with a new substring
• TRIM() removes leading and trailing spaces (or other specified characters) from a string

SQL By Rishabh Mishra 41 SQL By Rishabh Mishra 42

Most Used Aggregate Functions


Aggregate function performs a calculation on multiple values and
returns a single value.
And Aggregate functiona are often used with GROUP BY & SELECT
statement
GROUP BY & HAVING CLAUSE
• COUNT() returns number of values
• SUM() returns sum of all values
SQL Tutorial In Hindi-9
• AVG() returns average value
• MAX() returns maximum value
• MIN() returns minimum value
• ROUND() Rounds a number to a specified number of decimal places

SQL By Rishabh Mishra 43 SQL By Rishabh Mishra 44


GROUP BY Statement HAVING Clause
The GROUP BY statement group rows that have the same values into The HAVING clause is used to apply a filter on the result of GROUP BY based on the
summary rows. specified condition.
The WHERE clause places conditions on the selected columns, whereas the HAVING
It is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), clause places conditions on groups created by the GROUP BY clause
AVG()) to group the result-set by one or more columns Syntax
• Syntax SELECT column_name(s)
SELECT column_name(s) FROM table_name
FROM table_name WHERE condition(s)
GROUP BY column_name(s)
GROUP BY column_name(s); HAVING condition(s)
• Example
• Example SELECT mode, COUNT(amount) AS total
SELECT mode, SUM(amount) AS total FROM payment
GROUP BY mode
FROM payment
HAVING COUNT(amount) >= 3
GROUP BY mode ORDER BY total DESC

SQL By Rishabh Mishra 45 SQL By Rishabh Mishra 46

Quick Assignment: 01

Order of execution in SQL: TIMESTAMPS & EXTRACT


SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT
SQL Tutorial In Hindi-10
?
Answer in video’s comment
(no cheating)
SQL By Rishabh Mishra 47 SQL By Rishabh Mishra 48
TIMESTAMP TIMESTAMP functions/operators
The TIMESTAMP data type is used for values that Below are the TIMESTAMP functions and operators
contain both date and time parts in SQL:
• TIME contains only time, format HH:MI:SS • SHOW TIMEZONE
• DATE contains on date, format YYYY-MM-DD • SELECT NOW()
• YEAR contains on year, format YYYY or YY • SELECT TIMEOFDAY()
• TIMESTAMP contains date and time, format YYYY-MM-DD • SELECT CURRENT_TIME
HH:MI:SS
• SELECT CURRENT_DATE
• TIMESTAMPTZ contains date, time and time zone
SQL By Rishabh Mishra 49 SQL By Rishabh Mishra 50

EXTRACT Function
The EXTRACT() function extracts a part from a given date value.
Syntax: SELECT EXTRACT(MONTH FROM date_field) FROM Table
• YEAR
• QUARTER JOINS
• MONTH
• WEEK
• DAY
SQL Tutorial In Hindi-11
• HOUR
• MINUTE
• DOW – day of week
• DOY – day of year
SQL By Rishabh Mishra 51 SQL By Rishabh Mishra 52
SQL JOIN
TOPICS IN JOIN
• JOIN means to combine something.
• WHAT IS JOIN? • A JOIN clause is used to combine data from two or
• USE OF JOIN more tables, based on a related column between
them
• JOIN TYPES
• WHICH JOIN TO USE • Let’s understand the joins through an example:
• JOIN SYNTAX
• EXAMPLES IN SQL

SQL By Rishabh Mishra 53 SQL By Rishabh Mishra 54

JOIN Example JOIN Example


Question: How much amount was paid by customer ‘Madan’, what was Question: How much amount was
mode and payment date? paid by customer ‘Madan’, what
was mode and payment date?

payment
customer_id
amount
customer mode
customer_id Payment_date
first_name
last_name country
address_id address city_id Database Answer: Amount = 30,
city Mode = Credit Card,
address_id
address
country Date = 2020-04-27
city_id
postal_code
phone
SQL By Rishabh Mishra 55 SQL By Rishabh Mishra 56
TYPES OF JOINS INNER JOIN
• INNER JOIN
• Returns records that have
• LEFT JOIN matching values in both
• RIGHT JOIN tables
• FULL JOIN

SQL By Rishabh Mishra 57 SQL By Rishabh Mishra 58

INNER JOIN LEFT JOIN


• Syntax
SELECT column_name(s)
• Returns all records from the
FROM TableA
left table, and the matched
INNER JOIN TableB
records from the right table
ON TableA.col_name = TableB.col_name

• Example
SELECT *
FROM customer AS c
INNER JOIN payment AS p
ON c.customer_id = p.customer_id
SQL By Rishabh Mishra 59 SQL By Rishabh Mishra 60
LEFT JOIN RIGHT JOIN
• Syntax
SELECT column_name(s)
• Returns all records from the
FROM TableA
right table, and the matched
LEFT JOIN TableB
records from the left table
ON TableA.col_name = TableB.col_name

• Example
SELECT *
FROM customer AS c
LEFT JOIN payment AS p
ON c.customer_id = p.customer_id
SQL By Rishabh Mishra 61 SQL By Rishabh Mishra 62

RIGHT JOIN FULL JOIN


• Syntax
SELECT column_name(s)
• Returns all records when
FROM TableA
there is a match in either left
RIGHT JOIN TableB
or right table
ON TableA.col_name = TableB.col_name

• Example
SELECT *
FROM customer AS c
RIGHT JOIN payment AS p
ON c.customer_id = p.customer_id
SQL By Rishabh Mishra 63 SQL By Rishabh Mishra 64
FULL JOIN Which JOIN To Use
• Syntax • INNER JOIN: Returns records that have matching values in both tables
SELECT column_name(s) • LEFT JOIN: Returns all records from the left table, and the matched
FROM TableA records from the right table
FULL OUTER JOIN TableB • RIGHT JOIN: Returns all records from the right table, and the matched
ON TableA.col_name = TableB.col_name records from the left table
• FULL JOIN: Returns all records when there is a match in either left or
• Example right table
SELECT *
FROM customer AS c
FULL OUTER JOIN payment AS p
ON c.customer_id = p.customer_id
SQL By Rishabh Mishra 65 SQL By Rishabh Mishra 66

JOIN
CHEA SELF JOIN
T
SHEE SQL Tutorial In Hindi-12
T

SQL By Rishabh Mishra 67 SQL By Rishabh Mishra 68


SELF JOIN SELF JOIN example
• A self join is a regular join in which a table is joined to
itself Table: emp
• SELF Joins are powerful for comparing values in a
column of rows with the same table
• Syntax
SELECT column_name(s)
FROM Table AS T1
JOIN Table AS T2 • Find the name of respective managers for each
of the employees?
ON T1.col_name = T2.col_name
SQL By Rishabh Mishra 69 SQL By Rishabh Mishra 70

SELF JOIN example UNION


The SQL UNION clause/operator is used to combine/concatenate the results
of two or more SELECT statements without returning any duplicate rows and
keeps unique records
To use this UNION clause, each SELECT statement must have
• The same number of columns selected and expressions
• The same data type and
• Have them in the same order
• Syntax
SELECT column_name(s) FROM TableA
UNION
SELECT T2.empname, T1.empname SELECT column_name(s) FROM TableB
FROM emp AS T1 • Example
JOIN emp AS T2 SELECT cust_name, cust_amount from custA
ON T1.empid = T2.manager_id UNION
SELECT cust_name, cust_amount from custB
SQL By Rishabh Mishra 71 SQL By Rishabh Mishra 72
UNION ALL UNION Example
In UNION ALL everything is same as UNION, it
combines/concatenate two or more table but keeps all Table: custA Table: custB
records, including duplicates

• Syntax
SELECT column_name(s) FROM TableA
UNION ALL
SELECT column_name(s) FROM TableB

• Example
SELECT cust_name, cust_amount from custA
UNION ALL
SELECT cust_name, cust_amount from custB
SQL By Rishabh Mishra 73 SQL By Rishabh Mishra 74

SUB QUERY
A Subquery or Inner query or a Nested query allows us to
create complex query on the output of another query
• Sub query syntax involves two SELECT statements
SUB QUERY
• Syntax
SQL Tutorial In Hindi-13 SELECT column_name(s)
FROM table_name
WHERE column_name operator
( SELECT column_name FROM table_name WHERE ... );
SQL By Rishabh Mishra 75 SQL By Rishabh Mishra 76
SUB QUERY Example
Question: Find the details of customers, whose payment
amount is more than the average of total amount paid by all
customers

Divide above question into


WINDOWS FUNCTION
two parts:
1. Find the average amount SQL Tutorial In Hindi-14
2. Filter the customers
whose amount > average
amount

SQL By Rishabh Mishra 77 SQL By Rishabh Mishra 79

WINDOW FUNCTION WINDOW FUNCTION SYNTAX


• Window functions applies aggregate, ranking and analytic functions SELECT column_name(s),
over a particular window (set of rows). fun( ) OVER ( [ <PARTITION BY Clause> ]
• And OVER clause is used with window functions to define that [ <ORDER BY Clause> ]
window. [ <ROW or RANGE Clause> ] )
FROM table_name

Select a function Define a Window


• Aggregate functions • PARTITION BY
• Ranking functions • ORDER BY
• Analytic functions • ROWS

Give output one row per aggregation The rows maintain their separate identities

SQL By Rishabh Mishra 80 SQL By Rishabh Mishra 81


WINDOW FUNCTION TERMS WINDOW FUNCTION TYPES
Let’s look at some definitions: There is no official division of the SQL window functions into
• Window function applies aggregate, ranking and analytic functions categories but high level we can divide into three types
over a particular window; for example, sum, avg, or row_number
• Expression is the name of the column that we want the window Window Functions
function operated on. This may not be necessary depending on what
window function is used
• OVER is just to signify that this is a window function Aggregate Ranking Value/Analytic
• PARTITION BY divides the rows into partitions so we can specify which • SUM • ROW_NUMBER • LEAD
rows to use to compute the window function • AVG • RANK • LAG
• ORDER BY is used so that we can order the rows within each partition. • COUNT • DENSE_RANK • FIRST_VALUE
This is optional and does not have to be specified • MIN
• PERCENT_RANK • LAST_VALUE
• MAX
• ROWS can be used if we want to further limit the rows within our
partition. This is optional and usually not used
SQL By Rishabh Mishra 82 SQL By Rishabh Mishra 83

SELECT new_id, new_cat, AGGREGATE SELECT new_id, new_cat,


SUM(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Total", FUNCTION SUM(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Total",
AVG(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Average", Example AVG(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Average",
COUNT(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Count", COUNT(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Count",
MIN(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Min", MIN(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Min",
MAX(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Max" MAX(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Max"
FROM test_data FROM test_data

new_id new_cat Total Average Count Min Max AGGREGATE


new_id new_cat Total Average Count Min Max FUNCTION
100 Agni 2500 357.14286 7 100 700 Example
100 Agni 300 150 2 100 200
200 Agni 2500 357.14286 7 100 700
200 Agni 300 150 2 100 200
200 Vayu 2500 357.14286 7 100 700
500 Dharti 1200 600 2 500 700
300 Vayu 2500 357.14286 7 100 700
700 Dharti 1200 600 2 500 700
500 Vayu 2500 357.14286 7 100 700
200 Vayu 1000 333.33333 3 200 500
500 Dharti 2500 357.14286 7 100 700
300 Vayu 1000 333.33333 3 200 500
700 Dharti 2500 357.14286 7 100 700
500 Vayu 1000 333.33333 3 200 500
NOTE: Above we have used: “ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING”
SQL By Rishabh Mishra 84 which will give a SINGLE output based on all INPUT Values/PARTITION
SQL By Rishabh Mishra(if used) 85
SELECT new_id, RANKING SELECT new_id, ANALYTIC
ROW_NUMBER() OVER(ORDER BY new_id) AS "ROW_NUMBER", FUNCTION FIRST_VALUE(new_id) OVER( ORDER BY new_id) AS "FIRST_VALUE", FUNCTION
Example Example
RANK() OVER(ORDER BY new_id) AS "RANK", LAST_VALUE(new_id) OVER( ORDER BY new_id) AS "LAST_VALUE",
DENSE_RANK() OVER(ORDER BY new_id) AS "DENSE_RANK", LEAD(new_id) OVER( ORDER BY new_id) AS "LEAD",
PERCENT_RANK() OVER(ORDER BY new_id) AS "PERCENT_RANK" LAG(new_id) OVER( ORDER BY new_id) AS "LAG"
FROM test_data FROM test_data

new_id ROW_NUMBER RANK DENSE_RANK PERCENT_RANK new_id FIRST_VALUE LAST_VALUE LEAD LAG
100 1 1 1 0 100 100 100 200 null
200 2 2 2 0.166 200 100 200 200 100
200 3 2 2 0.166 200 100 200 300 200
300 4 4 3 0.5 300 100 300 500 200
500 5 5 4 0.666 500 100 500 500 300
500 6 5 4 0.666 500 100 500 700 500
700 7 7 5 1 700 100 700 null 500
NOTE: If you just want the single last value from whole column, use: “ROWS BETWEEN
SQL By Rishabh Mishra 86
UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING” SQL By Rishabh Mishra 87

Quick Assignment: WINDOW FUNCTION SELECT new_id, ANALYTIC


FUNCTION
LEAD(new_id, 2) OVER( ORDER BY new_id) AS "LEAD_by2", Assignment

Offset the LEAD and LAG values by 2 in the output columns ? LAG(new_id, 2) OVER( ORDER BY new_id) AS "LAG_by2"
FROM test_data
INPUT OUTPUT

new_id new_id LEAD LAG new_id LEAD_by2 LAG_by2


100 100 200 NULL 100 200 null
200 200 300 NULL 200 300 null
200 200 500 100 200 500 100
300 300 500 200 300 500 200
500 500 700 200 500 700 200
500 500 NULL 300 500 null 300
700 700 NULL 500 700 null 500

SQL By Rishabh Mishra 88 SQL By Rishabh Mishra 89


CASE Expression
• The CASE expression goes through conditions and returns
a value when the first condition is met (like if-then-else
statement). If no conditions are true, it returns the value
CASE EXPRESSION in the ELSE clause.

SQL Tutorial In Hindi-15 • If there is no ELSE part and no conditions are true, it
returns NULL.

• Also called CASE STATEMENT

SQL By Rishabh Mishra 90 SQL By Rishabh Mishra 91

CSV file CASE Statement Syntax


• 👉 payment csv file::https://bit.ly/41kJLRW • General CASE Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2 • Example:
WHEN conditionN THEN resultN SELECT customer_id, amount,
ELSE other_result CASE
END; WHEN amount > 100 THEN 'Expensive product'
WHEN amount = 100 THEN 'Moderate product'
ELSE 'Inexpensive product'
END AS ProductStatus
FROM payment
SQL By Rishabh Mishra 92 SQL By Rishabh Mishra 93
CASE Expression Syntax
• CASE Expression Syntax
CASE Expression
WHEN value1 THEN result1
WHEN value2 THEN result2
• Example: COMMON TABLE EXPRESSION
WHEN valueN THEN resultN SELECT customer_id,
ELSE other_result CASE amount
SQL Tutorial In Hindi-16
END; WHEN 500 THEN 'Prime Customer'
WHEN 100 THEN 'Plus Customer'
ELSE 'Regular Customer'
END AS CustomerStatus
FROM payment
SQL By Rishabh Mishra 94 SQL By Rishabh Mishra 95

Common Table Expression (CTE) CSV files


• A common table expression, or CTE, is a temporary • 👉 customer csv file: https://bit.ly/3xGABBR
named result set created from a simple SELECT statement • 👉 payment csv file: https://bit.ly/3Zc0GUV
that can be used in a subsequent SELECT statement
• We can define CTEs by adding a WITH clause directly
before SELECT, INSERT, UPDATE, DELETE, or MERGE
statement.
• The WITH clause can include one or more CTEs separated
by commas

SQL By Rishabh Mishra 96 SQL By Rishabh Mishra 97


Common Table Expression (CTE) CTE- Example
• Syntax 1. Example EASY
WITH my_cte AS (
1. Example Multiple CTEs
WITH my_cp AS (
2. Example Advance

WITH my_cte AS (
SELECT *, AVG(amount) OVER(ORDER BY p.customer_id)
WITH my_cte AS ( SELECT *, AVG(amount) OVER(ORDER BY
p.customer_id) AS "Average_Price",
AS "Average_Price",
COUNT(address_id) OVER(ORDER BY c.customer_id) AS
SELECT mode, MAX(amount) AS highest_price,
SUM(amount) AS total_price
"Count" FROM payment
COUNT(address_id) OVER(ORDER BY
SELECT a,b,c c.customer_id) AS "Count" FROM payment as p
)
GROUP BY mode

CTE query FROM payment as p


INNER JOIN customer AS c SELECT payment.*, my.highest_price, my.total_price

FROM Table1 ) INNER JOIN customer AS c


),
ON p.customer_id = c.customer_id FROM payment
JOIN my_cte my
ON payment.mode = my.mode
ON p.customer_id = c.customer_id my_ca AS (
SELECT a,c ) SELECT *
ORDER BY payment.mode

Main query SELECT first_name, last_name FROM customer as c

FROM my_cte FROM my_cte INNER JOIN address AS a


ON a.address_id = c.address_id
INNER JOIN country as cc
The name of this CTE is my_cte, and the CTE query is SELECT a,b,c FROM Table1. The CTE starts ON cc.city_id = a.city_id

with the WITH keyword, after which you specify the name of your CTE, then the content of the )
SELECT cp.first_name, cp.last_name, ca.city, ca.country, cp.amount
query in parentheses. The main query comes after the closing parenthesis and refers to the FROM my_ca as ca , my_cp as cp
CTE. Here, the main query (also known as the outer query) is SELECT a,c FROM my_cte
SQL By Rishabh Mishra 98 SQL By Rishabh Mishra 99

Now You Know All Concepts in SQL! ☺

Nest Step: Practice SQL Interview Questions YouTube: https://www.youtube.com/@RishabhMishraOfficial

Click Here Instagram: https://www.instagram.com/rishabhnmishra/

LinkedIn: https://www.linkedin.com/in/rishabhnmishra/

By Rishabh Mishra

SQL By Rishabh Mishra 100 101

You might also like