SQL
1
What is
Database?
Database is a system that allow users to
store and organise data
2
NoSQ
L
SQL
Databases
4
Introduction to
SQL
• What is SQL
• It’s applications
• SQL v/s NoSQL
• Types of SQL Commands
5
What is
SQL?
• SQL stands for Structured Query Language
• SQL lets you access and manipulate databases
6
SQL guidelines
SQL guidelines provided by a standard organization
American National Standards Institute (ANSI) in
1986, International Organization for
Standardization (ISO) in 1987.
7
SQL
Application
8
SQL v/s NoSQL
Aspect SQL (Relational) NoSQL (Non-relational)
Document-based, key-value, column-family, or
Data Structure Tables with rows and columns
graph-based
Schema Fixed schema (predefined structure) Flexible schema (dynamic and adaptable)
Scalability Vertically scalable (upgrading hardware) Horizontally scalable (adding more servers)
BASE-compliant (more available, less
Data Integrity ACID-compliant (strong consistency)
consistent)
Varies (e.g., MongoDB uses its own query
Query Language SQL (Structured Query Language)
language)
Better for large-scale data and fast read/write
Performance Efficient for complex queries and transactions
operations
Best for transactional systems (banking, ERP, Ideal for big data, real-time web apps, and data
Use Case
etc.) lakes
Examples MySQL, PostgreSQL, Oracle, MS SQL Server MongoDB, Cassandra, CouchDB, Neo4j
SQL
Commands
There are mainly 4 types of SQL commands:
DDL (Data Definition Language):
=> create, alter, and drop
DML (Data Manipulation Language):
=> select, insert, update and delete
DCL (Data Control Language):
=> grant and revoke permission to users
TCL(Transaction Control Language):
=> commit, rollback and savepoint.
10
SQL
Database
Structure
Columns Example
Tables
Data
(Rows & Columns) Rows
RDBMS
11
Sample Table – Customer
customer_id first_name last_name email address_id
1 Mary Smith [email protected] 234
2 Patricia Johnson [email protected] 654
3 Madan Mohan [email protected] 542
4 Barbara Jones [email protected] 754
5 Elizabeth Brown [email protected] 432
6 Jennifer Davis [email protected] 753
7 Maria Miller [email protected] 245
8 Susan Wilson [email protected] 214
DATA TYPES, PRIMARY & FOREIGN KEYS,
CONSTRAINTS
13
Data Types
Commonly Used data types in SQL:
• int: used for the integer value
• float: used to specify a decimal point number
• bool: used to specify Boolean values true and false
• char: fixed length string that can contain numbers, letters, and special
characters
• varchar: variable length string that can contain numbers, letters, and
special characters
• date: date format YYYY-MM-DD
• datetime: date & time combination, format is YYYY-MM-DD
hh:mm:ss
14
Constraint
s
Commonly used constraints in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE
• FOREIGN KEY - Prevents actions that would destroy links between tables (used
to link multiple tables together)
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very quickly
15
Operators In
SQL
The SQL reserved words and characters are called operators, which are
used with a WHERE clause in a SQL query
Most used operators:
1. Arithmetic operators : arithmetic operations on numeric values
Example: Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%)
2. Comparison operators: compare two different data of SQL table
• Example: Equal (=), Not Equal (!=), Greater Than (>), Greater Than Equals to (>=)
3. Logical operators: perform the Boolean operations
• Example: ALL, IN, BETWEEN, LIKE, AND, OR, NOT, ANY
4. Bitwise operators: perform the bit operations on the Integer
values
• Example: Bitwise AND (&), Bitwise OR(|) 16
Creating Database & Tables
17
Create
Table
The CREATE TABLE statement is used to create a new table in a database
• Syntax
CREATE TABLE table_name (
column_name1 datatype constraint,
column_name2 datatype constraint,
column_name3 datatype constraint,
);
18
Insert Values In
Table
The
•
INSERT INTO statement is used to insert new records in a table
Syntax
INSERT INTO TABLE_NAME
(column1, column2, column3,...columnN)
VALUES
(value1, value2, value3,...valueN);
19
Update Values In
Table
The UPDATE command is used to update existing rows in a table
Syntax
UPDATE TABLE_NAME
SET Column_name1 = value1, Column_name2 = value2
WHERE ID = value
Example
UPDATE customercase
SET first_name = 'Xam', address_id= 999
WHERE customer_id = 4;
20
Delete Values In
Table
The DELETE statement is used to delete existing records in a table
• Syntax
DELETE FROM table_name WHERE condition;
• Example
DELETE FROM customer
WHERE customer_id=
3;
21
ALTER Table
The ALTER TABLE statement is used to add, delete, or modify columns
in an existing table
• ALTER TABLE - ADD Column Syntax
ALTER TABLE table_name
ADD COLUMN column_name ;
• ALTER TABLE - DROP COLUMN Syntax
ALTER TABLE table_name
DROP COLUMN column_name;
• ALTER TABLE - ALTER/MODIFY COLUMN Syntax
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
22
Drop & Truncate
Table
The DROP TABLE command deletes a table in the database
• Syntax
DROP TABLE table_name;
The TRUNCATE TABLE command deletes the data inside a table, but
not the table itself
• Syntax
TRUNCATE TABLE table_name;
23
SELECT & WHERE
CLAUSE
24
SELECT
Statement
The SELECT statement is used to select data from a database.
• Syntax
SELECT column_name FROM table_name;
To select all the fields available in the table
• Syntax
SELECT * FROM table_name;
To select distinct/unique fields available in the table
• Syntax
SELECT DISTINCT Column_name FROM table_name;
25
WHERE
Clause
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition
• Syntax
SELECT column_name FROM table_name
WHERE conditions;
26
LIMIT
Clause
The LIMIT clause is used to set an upper limit on the number of tuples returned by
SQL.
Example: below code will return 5 rows of data
SELECT column_name FROM table_name
LIMIT 5;
ORDER BY Clause
The ORDER BY is used to sort the result-set in ascending (ASC) or descending
order (DESC).
Example: below code will sort the output data by column name in ascending
order
SELECT column_name FROM table_name
ORDER BY column_name ASC; 27
STRING FUNCTION
28
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
• SUBSTRING() extracts a substring from a string
• NOW() returns the current system date and time
• 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
29
Sample Table – PaymentCase
customer_id amount mode payment_date
1 60 Cash 24-09-2020
10 70 Mobile Payment 28-02-2021
11 80 Cash 01-03-2021
2 500 Credit Card 27-04-2020
8 100 Cash 26-01-2021
AGGREGATE FUNCTION
31
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
• COUNT() returns number of values
• SUM() returns sum of all values
• AVG() returns average value
• MAX() returns maximum value
• MIN() returns minimum value
• ROUND() Rounds a number to a specified number of decimal places
32
GROUP BY & HAVING
CLAUSE
33
GROUP BY
Statement
The GROUP BY statement group rows that have the same values into
summary rows.
It is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(),
AVG()) to group the result-set by one or more columns
• Syntax
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s);
• Example
SELECT mode, SUM(amount) AS total
FROM paymentcase
GROUP BY mode
34
HAVING
Clause
The HAVING clause is used to apply a filter on the result of GROUP BY based on the
specified condition.
The WHERE clause places conditions on the selected columns, whereas the
HAVING
clause places conditions on groups created by the GROUP BY clause
Syntax
SELECT column_name(s)
FROM table_name
WHERE condition(s)
GROUP BY
column_name(s)
HAVING condition(s)
• Example
SELECT mode, COUNT(amount) AS total
FROM paymentcase
GROUP BY mode
HAVING COUNT(amount) >= 3
ORDER BY total DESC 35
TIMESTAMPS & EXTRACT
36
TIMESTAMP
The TIMESTAMP data type is used for values that
contain both date and time parts
•TIME contains only time, format HH:MI:SS
•DATE contains on date, format YYYY-MM-DD
•YEAR contains on year, format YYYY or YY
•TIMESTAMP contains date and time, format YYYY-MM-DD
HH:MI:SS
37
TIMESTAMP
functions/operators
Below are the TIMESTAMP functions and operators
in SQL:
•SELECT CURDATE();
•SELECT CURTIME();
•SELECT NOW()
•SELECT CURRENT_TIMESTAMP();
38
EXTRACT
Function
The EXTRACT() function extracts a part from a given date value.
Syntax: SELECT MONTH(date_field) FROM Table
• YEAR
• MONTH
• DAY
• HOUR
• MINUTE
39
JOINS
40
SQL JOIN
•JOIN means to combine something.
•A JOIN clause is used to combine data from two
or more tables, based on a related column
between them
•Let’s understand the joins through an example:
41
TYPES OF JOINS
•INNER JOIN
•LEFT JOIN
•RIGHT JOIN
•FULL JOIN
42
customer and payment table creation
CREATE TABLE customer (
customer_id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
CREATE TABLE payment (
payment_id INT PRIMARY KEY,
customer_id INT,
amount DECIMAL(10, 2),
payment_date DATE,
FOREIGN KEY (customer_id) REFERENCES customer(customer_id)
);
Insert customer and payment
INSERT INTO customer (customer_id, name) VALUES
(1, ‘Rajesh'),
(2, ‘Sulthan'),
(3, ‘Ramesh’);
INSERT INTO payment (payment_id, customer_id, amount) VALUES
(101, 1, 500),
(102, 2, 300),
(103, 1, 200);
INNER
JOIN
•Returns records that have
matching values in both
tables
45
INNER
JOIN
• Syntax
SELECT column_name(s)
FROM TableA
INNER JOIN TableB
ON TableA.col_name =
TableB.col_name
• Example
SELECT *
FROM customer AS c
INNER JOIN payment AS p
ON c.customer_id = 46
LEFT
JOIN
•Returns all records from the
left table, and the matched
records from the right
table
47
LEFT JOIN
• Syntax
SELECT column_name(s)
FROM TableA
LEFT JOIN TableB
ON TableA.col_name =
TableB.col_name
• Example
SELECT *
FROM customer AS c
LEFT JOIN payment AS p
ON c.customer_id = 48
RIGHT
JOIN
•Returns all records from the
right table, and the matched
records from the left table
49
RIGHT
JOIN
• Syntax
SELECT column_name(s)
FROM TableA
RIGHT JOIN TableB
ON TableA.col_name =
TableB.col_name
• Example
SELECT *
FROM customer AS c
RIGHT JOIN payment AS p
ON c.customer_id = 50
UNIO
NThe 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 column_name(s) FROM TableB
• Example
SELECT cust_name, cust_amount from
custA
UNION
51
SELECT cust_name, cust_amount from
UNION
ALL
In UNION ALL everything is same as UNION, it
combines/concatenate two or more table but keeps all
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
52
from custB
FULL
JOIN
•Returns all records when
there is a match in either left
or right table
53
FULL JOIN
MySQL does not support FULL JOIN (or FULL OUTER JOIN) directly, but you can
achieve the same result using a combination of LEFT JOIN, RIGHT JOIN, and UNION.
Syntax
SELECT *
FROM customersjoin c
LEFT JOIN paymentsjoin p ON c.customer_id = p.customer_id
UNION
SELECT *
FROM customersjoin c
RIGHT JOIN paymentsjoin p ON c.customer_id = p.customer_id
WHERE c.customer_id IS NULL;
54
Which JOIN To
Use
• INNER JOIN: Returns records that have matching values in both tables
• LEFT JOIN: Returns all records from the left table, and the matched
records from the right table
• RIGHT JOIN: Returns all records from the right table, and the matched
records from the left table
• FULL JOIN: Returns all records when there is a match in either left or
right table
55
SELF JOIN
•A self join is a regular join in which a table is joined
to itself
•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
ON T1.col_name =
T2.col_name 56
SELF JOIN
example
Table: emp
• Find the name of respective managers for each
of the employees?
57
SELF JOIN
example
SELECT T2.empname, T1.empname
FROM emp AS T1
JOIN emp AS T2
ON T1.empid =
T2.manager_id 58
customersjoin
customer_id first_name last_name address_id
1 Mary Smith 5
3 Linda Williams 7
4 Barbara Jones 8
2 Madan Mohan 6
17 R Madhav 9
paymentsjoin
customer_id amount mode payment_date
1 60 Cash 24-09-2020
11 80 Cash 01-03-2021
2 500 Credit Card 27-04-2020
8 100 Cash 26-01-2021
7 20 Mobile Payment 01-02-2021
17 250 Credit Card 01-04-2021
10 70 Mobile Payment 28-02-2021
SUB QUERY
60
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
•Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name
operator
( SELECT
column_name
61
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
two parts:
1. Find the average
amount
2. Filter the customers
whose amount > average
amount
62
WINDOWS FUNCTION
79
WINDOW
FUNCTION
• Window functions applies aggregate, ranking and analytic functions
over a particular window (set of rows).
• And OVER clause is used with window functions to define that
window.
Give output one row per aggregation The rows maintain their separate identities
80
WINDOW FUNCTION
SYNTAX
SELECT column_name(s),
fun( ) OVER ( [ <PARTITION BY Clause> ]
[ <ORDER BY Clause> ]
[ <ROW or RANGE Clause> ]
FROM table_name
)
Select a function Define a Window
• Aggregate functions • PARTITION BY
• Ranking functions • ORDER BY
• Analytic functions • ROWS
81
WINDOW FUNCTION
TERMS
Let’s look at some definitions:
• Window function applies aggregate, ranking and analytic functions
over a particular window; for example, sum, avg, or row_number
• Expression is the name of the column that we want the window
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
• PARTITION BY divides the rows into partitions so we can specify which
rows to use to compute the window function
• ORDER BY is used so that we can order the rows within each partition.
This is optional and does not have to be specified
• ROWS can be used if we want to further limit the rows within our
partition. This is optional and usually not used
82
WINDOW FUNCTION
TYPES
There is no official division of the SQL window functions into
categories but high level we can divide into three types
Window Functions
Aggregate Ranking Value/Analytic
• SUM • ROW_NUMBER • LEAD
• AVG • RANK • LAG
• COUNT
• DENSE_RANK • FIRST_VALUE
• MIN
• PERCENT_RANK • LAST_VALUE
• MAX
83
SELECT new_id, new_cat, AGGREGAT
SUM(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Total", E
AVG(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Average", FUNCTION
COUNT(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Count", Example
MIN(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Min",
MAX(new_id) OVER( PARTITION BY new_cat ORDER BY new_id ) AS "Max"
FROM test_data
new_id new_cat Total Average Count Min Max
100 Agni 300 150 2 100 200
200 Agni 300 150 2 100 200
500 Dharti 1200 600 2 500 700
700 Dharti 1200 600 2 500 700
200 Vayu 1000 333.33333 3 200 500
300 Vayu 1000 333.33333 3 200 500
500 Vayu 1000 333.33333 3 200 500
84
SELECT new_id, new_cat,
SUM(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Total",
AVG(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Average",
COUNT(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Count",
MIN(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Min",
MAX(new_id) OVER( ORDER BY new_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS "Max"
FROM test_data
new_id new_cat Total Average Count Min Max AGGREGAT
E
100 Agni 2500 357.14286 7 100 700
FUNCTION
200 Agni 2500 357.14286 7 100 700 Example
200 Vayu 2500 357.14286 7 100 700
300 Vayu 2500 357.14286 7 100 700
500 Vayu 2500 357.14286 7 100 700
500 Dharti 2500 357.14286 7 100 700
700 Dharti 2500 357.14286 7 100 700
NOTE: Above we have used: “ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING”
which will give a SINGLE output based on all INPUT 85
THANK YOU