SQL
SQL
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
store and organise data Data stored less data Stores large amount of data
Good for one time analysis, quick charts Can automate tasks
SQL Databases
RDBMS
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
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 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;
• Syntax
SELECT DISTINCT Column_name FROM table_name;
SQL By Rishabh Mishra 33 SQL By Rishabh Mishra 34
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
Quick Assignment: 01
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
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
• 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
• 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
• 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
Give output one row per aggregation The rows maintain their separate identities
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
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
SQL Tutorial In Hindi-15 • If there is no ELSE part and no conditions are true, it
returns NULL.
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
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
LinkedIn: https://www.linkedin.com/in/rishabhnmishra/
By Rishabh Mishra