Learning SQL Zero To Hero
Learning SQL Zero To Hero
ZERO TO HERO
10 Days Of SQL
@talhakhan 1
But first, you need to
understand
THE BASICS
Let’s start with databases
@talhakhan 2
1: DATABASES
A database is a collection of
RELATED information
@talhakhan 3
2: DATABASE APPLICATIONS
Banking: transactions
Airlines: reservations, schedules
Universities: registration, grades
Sales: customers, products, purchases
Online retailers: order tracking, customized
recommendations
Manufacturing: production, inventory, orders, supply
chain
Human resources: employee records, salaries, tax
deductions
@talhakhan 4
3: WHAT IS DBMS?
@talhakhan 5
4: C.R.U.D
@talhakhan 6
5: TYPES OF DATABASES (Traditional)
@talhakhan 7
6: Relational Databases
Department Table
DepartmentID DepartmentName
1 HR
2 Sales
3 IT
6 Finance
@talhakhan 8
7: RDBMS
▪ MySQL
▪ Oracle
▪ PostgreSQL
▪ Microsoft SQL Server (MSS)
@talhakhan 9
8: SQL
1. DQL
• Data Query Language
• Used to query (request) the database for
information
• Get information that is already there
• SELECT Statements
2. DDL
• Data Definition Language
• Used for defining database schemas
• CREATE, ALTER, DROP, TRUNCATE, RENAME
@talhakhan 11
10: Types of SQL (continued)
3. DCL
• Data Control Language
• Used for controlling access to the data in the
database
• User access and permission management
• GRANT, REVOKE
4. DML
• Data Manipulation Language
• Used for inserting, updating, and deleting data
from the database
• INSERT, DELETE, UPDATE
@talhakhan 12
11: Common Data Types
Some examples:
• INT – Whole Numbers
• DECIMAL(M,N) / FLOAT – Decimal Numbers
• VARCHAR(32) – String of text of length 32
• BLOB – Binary Large Objects, Stores large data
• DATE – ‘YYYY-MM-DD’
• TIMESTAMP – ‘YYYY’MM’DD HH:MM:SS’ used for
recording different events, transactions,
continuous values etc.
@talhakhan 13
11: Where is data really stored?
@talhakhan 14
12: SQL Query Order of execution
SQL queries are executed in a specific logical order, which is particularly important
to understand when dealing with complex queries, including those with JOIN
operations.
The query starts with the FROM clause, identifying the tables, and performs any
JOIN operations.
2️⃣ WHERE:
Example: WHERE Country = 'USA' filters the results to include only orders from
customers in the USA. Country is a column in the Customers table.
@talhakhan 15
13: SQL Query Order of execution
5️⃣ SELECT: The query now selects the columns that are to be
displayed in the result set. This is where the actual data from the rows
is retrieved, based on the previous steps.
@talhakhan 16
14: SQL Query Order of execution
This sorts the result set in ascending or descending order. The sorting
is done after the data has been selected.
Finally, these clauses are used to limit the number of rows returned
and to specify a starting point for the row count (common in
pagination scenarios).
@talhakhan 17
RECAP
@talhakhan 18
KEYS, C.R.U.D & JOINS
@talhakhan 19
Consider the schema of
A HOSPITAL DATABASE
@talhakhan 20
But wait, what is a
SCHEMA?
@talhakhan 21
1: PRIMARY KEY
Example:
In the patients table, patient_id is the primary key, ensuring
each patient is uniquely identified.
@talhakhan 22
2: FOREIGN KEY (FK)
Example:
'attending_doctor_id' in 'admissions’ table references
'doctor_id' in 'doctors’.
@talhakhan 23
3: COMPOSITE KEY
Example:
@talhakhan 24
4: CREATING TABLE
@talhakhan 26
6: UPDATING RECORDS
UPDATE patients
SET city = 'New City'
WHERE patient_id = 123;
@talhakhan 27
7: DELETING RECORDS OR TABLES
-- Deleting records
DELETE FROM patients
WHERE patient_id = 123;
-- Deleting a table
DROP TABLE IF EXISTS old_patients;
Use when you need data from multiple tables to be presented in a single query result set.
LEFT JOIN: Selects all records from the left table, with matching records from the right table.
RIGHT JOIN: Selects all records from the right table, with matching records from the left
table.
FULL OUTER JOIN: Selects all records when there is a match in either left or right table.
29
@talhakhan
9: Database Description
-- For MySQL
DESCRIBE patients;
@talhakhan 31
Let’s take an example of
PATIENTS TABLE
patient_id first_name last_name gender birth_date city province_id allergies height weight
@talhakhan 32
1: WHERE Clause
SELECT
patient_id,
first_name,
last_name,
weight
FROM patients
WHERE weight > 80;
The query above selects all columns for patients who weigh more than 80 kilograms.
@talhakhan 33
2: COMPARISON OPERATORS
Not Equal To (<> or !=): It tests if two values are not equal.
-- To select all patients who do not live in New York
SELECT *
FROM patients
WHERE city != 'New York’;
Greater Than (>): This operator checks if the value on the left is greater than the one on
the right
-- To select patients taller than 170cm
SELECT *
FROM patients
WHERE height > 170; 34
@talhakhan
3: COMPARISON OPERATORS (cont’d)
Greater Than or Equal To (>=): This operator checks if the left value is greater than or equal to
the right value.
--to select cardiologists with a doctor_id of 10 or higher.
Less Than or Equal To (<=): It checks if the left value is less than or equal to the right value.
-- to select admissions on or before the end of the year 2021
35
@talhakhan
4: LOGICAL OPERATORS
AND: This operator allows you to combine two or more conditions, and it
returns true only if all conditions are true. It's used to narrow down the
search results.
-- To select records where the patient was discharged and diagnosed with
Appendicitis.
SELECT * FROM admissions WHERE discharge_date IS NOT NULL AND
diagnosis = 'Appendicitis’;
37
@talhakhan
6: LOGICAL OPERATORS (cont’d)
-- To select all patients whose first name starts with the letter ‘J’.
The LIKE clause uses wildcards – more on this later.
38
@talhakhan
7: ARITHMETIC OPERATORS
--To add together the height and weight for each patient. (this example
is not practical, but just based on what we have in the patients table)
SELECT
patient_id,
first_name,
height + weight AS combined_dimension
FROM patients;
39
@talhakhan
8: ARITHMETIC OPERATORS (Cont’d)
40
@talhakhan
TEXT FUNCTIONS
@talhakhan 41
1: LEN
Examples
1. FirstNameLength
2. CityLength
3. AllergiesLength
Examples ---
1. DiagnosisStart
SELECT SUBSTRING('Bronchitis', 1, 5) AS DiagnosisStart;
-- Output: 'Bronc'
2. FirstNamePart
SELECT SUBSTRING('Alexander', 3, 3) AS FirstNamePart;
-- Output: 'exa'
3. ProvinceEnd
SELECT SUBSTRING('Ontario', LEN('Ontario') - 4, 5) AS
ProvinceEnd; @talhakhan 43
-- Output: 'ario'
3: CONCAT
Examples
1. FullName
SELECT CONCAT('John', ‘ ', 'Doe') AS FullName;
-- Output: 'John Doe'
2. DoctorFullName
SELECT CONCAT(‘Dr. ', 'John', ‘ ', 'Doe') AS DoctorFullName;
-- Output: 'Dr. John Doe'
3. AdmissionDetails
SELECT CONCAT('Admitted: ', '2023-01-01', ', Discharged: ', '2023-
01-10') AS AdmissionDetails;
@talhakhan 44
-- Output: 'Admitted: 2023-01-01, Discharged: 2023-01-10'
4: TRIM
Examples
Assuming 'first_name' and 'province_name' have leading/trailing
spaces
1. CleanFirstName
SELECT TRIM(' John ') AS CleanFirstName;
-- Output: 'John'
2. CleanLastName
SELECT TRIM(' Doe ') AS CleanLastName;
-- Output: 'Doe'
3. CleanProvinceName
SELECT TRIM(' Ontario ') AS CleanProvinceName;
@talhakhan 45
-- Output: 'Ontario'
5: REGEXP
Example 1
SELECT first_name
FROM doctors
WHERE first_name REGEXP '^Jo’;
+------------+
| first_name |
+------------+
| John |
| Joanna |
| Johnny | @talhakhan 46
+------------+
6: REGEXP
SELECT diagnosis
FROM admissions
WHERE diagnosis REGEXP '\\d{4}-\\d{2}-\\d{2}';
+---------------------------------------------+
| diagnosis |
+---------------------------------------------+
| Diagnosed with Hypertension on 2023-01-10 |
| Routine check-up on 2024-03-15 |
+---------------------------------------------+
@talhakhan 47
7: UPPER & LOWER
Examples
1. LastNameUpper
SELECT UPPER('smith') AS LastNameUpper;
-- Output: 'SMITH’
2. LastNameLower
SELECT LOWER(‘SMITH') AS LastNameLower;
-- Output: ‘smith'
@talhakhan 48
CASES & SUBQUERIES
@talhakhan 49
1: CASES
Example 1
-- Assigning a classification based on age:
SELECT
first_name,
last_name,
CASE
WHEN birth_date >= '2000-01-01' THEN 'Gen Z’
WHEN birth_date < '2000-01-01' AND birth_date >= '1980-01-01'
THEN 'Millennial’
ELSE 'Other'
END AS generation
FROM patients;
The CASE statement ends with the keyword END to signify the end of the
conditional logic. Following END, you can use AS to give a name (alias) to the
new column generated by the CASE statement.
@talhakhan 50
2: CASES (Cont’d)
Example 2
-- Creating a custom sorting order
SELECT
patient_id,
city,
CASE city
WHEN 'Barrie' THEN 1
WHEN 'Dundas' THEN 2
WHEN 'Hamilton' THEN 3
ELSE 4
END AS custom_order
FROM patients
ORDER BY custom_order;
@talhakhan 51
3: Subqueries
Example 1
-- Finding doctors who have treated patients with a specific allergy:
SELECT DISTINCT
doctor_id,
first_name,
last_name
FROM doctors
WHERE doctor_id IN
(
SELECT attending_doctor_id
FROM admissions
JOIN patients ON admissions.patient_id = patients.patient_id
WHERE allergies = 'Penicillin’
);
@talhakhan 52
4: Subqueries (Cont’d)
Example 2
-- Updating records based on a condition from another
table
UPDATE patients
SET city = 'Toronto'
WHERE patient_id IN
(
SELECT patient_id
FROM admissions
WHERE discharge_date < '2021-01-01’
);
@talhakhan 53
5: PRACTICE QUESTIONS
54
@talhakhan
CTEs
@talhakhan 55
What are CTEs?
And why are they so important?
@talhakhan 56
1: What are CTEs?
@talhakhan 57
2: And why are they so Important?
@talhakhan 58
3: When to use CTEs?
@talhakhan 59
4: Syntax
WITH CTE_Name AS
(
-- CTE query here
)
@talhakhan 60
Consider the schema of
A HOSPITAL DATABASE
@talhakhan 61
5: EXAMPLE 1
WITH DoctorAdmissions AS
(
SELECT attending_doctor_id,
COUNT(*) AS AdmissionCount
FROM admissions
GROUP BY attending_doctor_id
)
SELECT
d.doctor_id,
d.first_name,
d.last_name,
da.AdmissionCount
FROM doctors d
LEFT JOIN DoctorAdmissions da ON d.doctor_id =
da.attending_doctor_id;
@talhakhan 62
6: EXAMPLE 2
WITH MultipleAdmissions AS
(
SELECT patient_id
FROM admissions
GROUP BY patient_id
HAVING COUNT(admission_id) > 1
)
SELECT
p.patient_id,
p.first_name,
p.last_name
FROM patients p
INNER JOIN MultipleAdmissions ma ON
p.patient_id = ma.patient_id;
@talhakhan 63
7: RECURSIVE CTEs
@talhakhan 64
8: STRUCTURE OF RECURSIVE CTEs
@talhakhan 65
9: Syntax OF RECURSIVE CTEs
UNION ALL
-- Recursive member
SELECT ....
FROM ....
JOIN CTE_Name ON ...
WHERE ....
)
SELECT * FROM CTE_Name;
@talhakhan 66
10: When to Use Recursive CTEs
@talhakhan 67
11: PRACTICE QUESTIONS
68
@talhakhan
Stored Procedures
& Triggers
@talhakhan 69
What are Stored Procedures &
Triggers?
And how can they make my life easier?
@talhakhan 70
1: What are Stored Procedures?
@talhakhan 71
2: And why are they used?
@talhakhan 72
3: Syntax
@talhakhan 73
4: Calling stored procedures
SQL SERVER:
EXEC procedure_name;
-- Or if the procedure takes parameters:
EXEC procedure_name @param1, @param2, ...;
MySQL:
CALL procedure_name();
-- Or if the procedure takes parameters:
CALL procedure_name(param1, param2, ...);
PostgreSQL:
SELECT procedure_name();
-- Or if the procedure takes parameters:
SELECT procedure_name(param1, param2, ...);
@talhakhan 74
Consider the schema of
A HOSPITAL DATABASE
@talhakhan 75
5: EXAMPLE 1
@talhakhan 77
7: Triggers
@talhakhan 78
8: Syntax of Triggers
@talhakhan 79
9: Why do we use Triggers?
@talhakhan 80
10: EXAMPLE 3
83
@talhakhan
Best Practices & Query
Optimization
@talhakhan 84
How to write SQL queries
efficiently?
And make you stand out?
@talhakhan 85
1: Query Design and Structure:
@talhakhan 86
2: Query Design and Structure (cont’d)
@talhakhan 88
4: Indexing and Data Retrieval
@talhakhan 89
4: Performance Tuning
@talhakhan 90
6: Data Management
@talhakhan 91
7: Server & Resource Management
@talhakhan 92
TheDataDialogue
Mini Project
@talhakhan 93
If you have made so far
You already are a SQL intermediate user
@talhakhan 94
Bookstore Inventory and Sales
Analysis
@talhakhan 95
The Database Schema
Courtesy of databasestar
@talhakhan 96
GOAL
@talhakhan 97
Key Objectives
1. Analyze sales trends and inventory.
2. Automate data management tasks.
3. Generate actionable business insights.
@talhakhan 98
Where is the data?
You can download it at
https://github.com/thedatadialogue/Databases
@talhakhan 99
Project Tasks Breakdown
@talhakhan 100
BASIC TASK: 1
Task:
• Retrieve a list of all books, including their authors and
categories.
• Hint: Join books, book_authors, authors, and
categories tables.
@talhakhan 101
BASIC TASK: 2
Task:
• Calculate the total sales (quantity sold) for each book.
• Hint: Use order_items table and join with books
@talhakhan 102
BASIC TASK: 3
Task:
• Determine which book category is most popular based
on the quantity of books sold.
• Hint: Aggregate sales data from order_items and join
with books and categories
@talhakhan 103
INTERMEDIATE TASK 1:
Task:
• Analyze the total sales amount for each month.
• Hint: Use orders and order_items. Extract month and
year from order_date.
@talhakhan 104
INTERMEDIATE TASK 2:
Task:
• Identify the top 5 authors based on the number of
books sold.
• Hint: Join books, book_authors, authors, and
order_items
@talhakhan 105
INTERMEDIATE TASK 3:
Task:
• Calculate the average order value for each customer.
• Hint: Aggregate order totals in orders and average them
for each customer in customers
@talhakhan 106
ADVANCED TASK 1:
Task:
• Determine how sales have trended over the years.
• Hint: Use window functions with orders and
order_items to analyze year-over-year trends.
@talhakhan 107
ADVANCED TASK 2:
Task:
• Identify customers eligible for a loyalty program based
on their order history.
• Hint: Use orders and order_items to calculate total
purchases per customer, then set a threshold for loyalty
eligibility.
@talhakhan 108
CTEs, CASES, Stored Procedures and Subqueries
@talhakhan 109
KEEP PRACTICING
UPSKILL YOURSELF
AND GOOD THINGS AWAIT YOU
Stay tuned
@talhakhan 110