DA charts.pdf
607.4 KB
π Master Data Visualization & Charts for Data Analysis!
Want to make your data analysis more insightful with stunning visualizations? πβ¨ Learn how to use charts, graphs, and dashboards to uncover hidden patterns and tell compelling data stories!
Turn your raw data into clear, meaningful, and powerful visual insights today! π₯
Want to make your data analysis more insightful with stunning visualizations? πβ¨ Learn how to use charts, graphs, and dashboards to uncover hidden patterns and tell compelling data stories!
Turn your raw data into clear, meaningful, and powerful visual insights today! π₯
π₯4π2
Day 1: Introduction to SQL and Relational Databases
Welcome to Day 1 of your SQL learning journey! π
SQL (Structured Query Language) is the language of databases and is widely used for managing and analyzing data. Whether you're aiming for a career in Data Science, Data Analysis, Web Development, or Finance, SQL is an essential skill to master.
---
π What is SQL?
SQL stands for Structured Query Language and is used to communicate with databases. It helps you store, retrieve, manipulate, and manage data in a structured way.
Imagine a library database where details of books (title, author, genre, availability) are stored in tables. With SQL, you can:
β Find a book by its title
β Get a list of all books by a specific author
β Check how many books are available in a genre
β Add new books to the library collection
β Delete outdated records
---
π What is a Database?
A database is an organized collection of data that allows easy access, management, and updating.
There are two main types of databases:
1οΈβ£ Relational Databases (RDBMS): Data is stored in tables (like Excel). Examples: MySQL, PostgreSQL, SQL Server, SQLite.
2οΈβ£ Non-Relational Databases (NoSQL): Data is stored in key-value pairs, JSON, or documents. Examples: MongoDB, Firebase.
SQL works with Relational Databases (RDBMS).
---
π What is a Table?
A table is like a spreadsheet in Excel, with rows and columns.
π Example: A simple "Students" table
| Student_ID | Name | Age | Grade |
|------------|-------|-----|--------|
| 1 | Alex | 18 | A |
| 2 | Emma | 19 | B |
| 3 | John | 18 | A |
Each row represents a student, and each column stores a specific type of data (ID, Name, Age, Grade).
---
π SQL Commands Overview
SQL has different types of commands to manage data:
πΉ Data Query Language (DQL) β Used for fetching data
πΈ
πΉ Data Manipulation Language (DML) β Used for modifying data
πΈ
πΈ
πΈ
πΉ Data Definition Language (DDL) β Used for creating and modifying tables
πΈ
πΈ
πΈ
πΉ Data Control Language (DCL) β Used for user permissions
πΈ
πΈ
πΉ Transaction Control Language (TCL) β Used for managing transactions
πΈ
πΈ
---
π Setting Up a Database
To practice SQL, you need a database environment. You can use:
1οΈβ£ Online SQL Editors β No installation needed
- [SQL Fiddle](http://sqlfiddle.com/)
- [W3Schools SQL Editor](https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all)
2οΈβ£ Install a Database Software
- MySQL (Popular for beginners) β [Download](https://www.mysql.com/downloads/)
- PostgreSQL (Advanced features) β [Download](https://www.postgresql.org/download/)
- SQL Server (Used in enterprises) β [Download](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
---
π Writing Your First SQL Query
Letβs retrieve all data from a Students table using the
Explanation:
-
-
-
---
π― Task for Today
1οΈβ£ Understand the basic SQL commands mentioned above.
2οΈβ£ Try an online SQL editor and execute
3οΈβ£ Install MySQL or PostgreSQL (optional, but recommended).
---
π Thatβs it for Day 1! Tomorrow, weβll learn about SQL Data Types and start writing basic queries. π
π‘ Like & comment if you're excited to continue this series! πβ€οΈ
Welcome to Day 1 of your SQL learning journey! π
SQL (Structured Query Language) is the language of databases and is widely used for managing and analyzing data. Whether you're aiming for a career in Data Science, Data Analysis, Web Development, or Finance, SQL is an essential skill to master.
---
π What is SQL?
SQL stands for Structured Query Language and is used to communicate with databases. It helps you store, retrieve, manipulate, and manage data in a structured way.
Imagine a library database where details of books (title, author, genre, availability) are stored in tables. With SQL, you can:
β Find a book by its title
β Get a list of all books by a specific author
β Check how many books are available in a genre
β Add new books to the library collection
β Delete outdated records
---
π What is a Database?
A database is an organized collection of data that allows easy access, management, and updating.
There are two main types of databases:
1οΈβ£ Relational Databases (RDBMS): Data is stored in tables (like Excel). Examples: MySQL, PostgreSQL, SQL Server, SQLite.
2οΈβ£ Non-Relational Databases (NoSQL): Data is stored in key-value pairs, JSON, or documents. Examples: MongoDB, Firebase.
SQL works with Relational Databases (RDBMS).
---
π What is a Table?
A table is like a spreadsheet in Excel, with rows and columns.
π Example: A simple "Students" table
| Student_ID | Name | Age | Grade |
|------------|-------|-----|--------|
| 1 | Alex | 18 | A |
| 2 | Emma | 19 | B |
| 3 | John | 18 | A |
Each row represents a student, and each column stores a specific type of data (ID, Name, Age, Grade).
---
π SQL Commands Overview
SQL has different types of commands to manage data:
πΉ Data Query Language (DQL) β Used for fetching data
πΈ
SELECT
β Retrieve data from tables πΉ Data Manipulation Language (DML) β Used for modifying data
πΈ
INSERT
β Add new data πΈ
UPDATE
β Modify existing data πΈ
DELETE
β Remove data πΉ Data Definition Language (DDL) β Used for creating and modifying tables
πΈ
CREATE TABLE
β Create a new table πΈ
ALTER TABLE
β Modify table structure πΈ
DROP TABLE
β Delete a table πΉ Data Control Language (DCL) β Used for user permissions
πΈ
GRANT
β Give permissions πΈ
REVOKE
β Remove permissions πΉ Transaction Control Language (TCL) β Used for managing transactions
πΈ
COMMIT
β Save changes permanently πΈ
ROLLBACK
β Undo changes ---
π Setting Up a Database
To practice SQL, you need a database environment. You can use:
1οΈβ£ Online SQL Editors β No installation needed
- [SQL Fiddle](http://sqlfiddle.com/)
- [W3Schools SQL Editor](https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all)
2οΈβ£ Install a Database Software
- MySQL (Popular for beginners) β [Download](https://www.mysql.com/downloads/)
- PostgreSQL (Advanced features) β [Download](https://www.postgresql.org/download/)
- SQL Server (Used in enterprises) β [Download](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
---
π Writing Your First SQL Query
Letβs retrieve all data from a Students table using the
SELECT
statement. SELECT * FROM Students;
Explanation:
-
SELECT
β Tells SQL to retrieve data -
*
β Means "all columns" -
FROM Students
β Specifies the table name ---
π― Task for Today
1οΈβ£ Understand the basic SQL commands mentioned above.
2οΈβ£ Try an online SQL editor and execute
SELECT * FROM Students;
3οΈβ£ Install MySQL or PostgreSQL (optional, but recommended).
---
π Thatβs it for Day 1! Tomorrow, weβll learn about SQL Data Types and start writing basic queries. π
π‘ Like & comment if you're excited to continue this series! πβ€οΈ
Sqlfiddle
SQL Fiddle - Online SQL Compiler for learning & practice
Discover our free online SQL editor enhanced with AI to chat, explain, and generate code. Support SQL Server, MySQL, MariaDB, PostgreSQL, and SQLite.
π15π₯5
Day 2: SQL Data Types and Writing Basic Queries
Welcome to Day 2 of your SQL learning journey! π
Today, weβll cover two important topics:
β Data Types in SQL β Understanding different types of data in a database
β Writing Basic SQL Queries β Learning how to retrieve data using SQL
By the end of this lesson, youβll be able to create a table and write your first SQL query to fetch data! π
---
π What Are Data Types in SQL?
A data type defines the kind of data a column can store. Each column in a table must have a specific data type to ensure that data is stored correctly.
For example, a "Name" column should store text, while an "Age" column should store numbers.
---
π Common SQL Data Types (MySQL, PostgreSQL, SQL Server)
1οΈβ£ Numeric Data Types (Used for storing numbers)
| Data Type | Description | Example |
|-----------|------------|---------|
|
|
|
πΉ Example: If youβre storing student ages, use
---
2οΈβ£ String (Text) Data Types
| Data Type | Description | Example |
|-----------|------------|---------|
|
|
|
πΉ Example: A column storing names should be
---
3οΈβ£ Date and Time Data Types
| Data Type | Description | Example |
|-----------|------------|---------|
|
|
|
|
πΉ Example: If youβre storing a studentβs birth date, use
---
π Creating a Table in SQL
Now that we understand data types, letβs create a table for our students.
πΉ Explanation:
-
-
-
-
-
-
---
π Writing Basic SQL Queries
Now, letβs insert some data and retrieve it using SQL queries.
1οΈβ£ Inserting Data into a Table
πΉ Explanation:
-
-
-
Now, letβs add a few more students:
---
2οΈβ£ Retrieving Data Using `SELECT` Statement
To see all student records, use:
πΉ Explanation:
-
-
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
---
Welcome to Day 2 of your SQL learning journey! π
Today, weβll cover two important topics:
β Data Types in SQL β Understanding different types of data in a database
β Writing Basic SQL Queries β Learning how to retrieve data using SQL
By the end of this lesson, youβll be able to create a table and write your first SQL query to fetch data! π
---
π What Are Data Types in SQL?
A data type defines the kind of data a column can store. Each column in a table must have a specific data type to ensure that data is stored correctly.
For example, a "Name" column should store text, while an "Age" column should store numbers.
---
π Common SQL Data Types (MySQL, PostgreSQL, SQL Server)
1οΈβ£ Numeric Data Types (Used for storing numbers)
| Data Type | Description | Example |
|-----------|------------|---------|
|
INT
| Stores whole numbers | 25, 100, -50 | |
DECIMAL(p, s)
| Stores decimal numbers with precision | 12.34, 99.99 | |
FLOAT
/ REAL
| Stores floating-point numbers | 1.23, 3.14 | πΉ Example: If youβre storing student ages, use
INT
. If youβre storing bank balances, use DECIMAL
. ---
2οΈβ£ String (Text) Data Types
| Data Type | Description | Example |
|-----------|------------|---------|
|
CHAR(n)
| Fixed-length string (n characters) | 'A', 'USA' | |
VARCHAR(n)
| Variable-length string (up to n characters) | 'John Doe', 'Hello World' | |
TEXT
| Large text data | 'This is a long description...' | πΉ Example: A column storing names should be
VARCHAR(50)
, meaning it can hold up to 50 characters. ---
3οΈβ£ Date and Time Data Types
| Data Type | Description | Example |
|-----------|------------|---------|
|
DATE
| Stores only the date (YYYY-MM-DD) | '2025-02-02' | |
TIME
| Stores only the time (HH:MM:SS) | '14:30:00' | |
DATETIME
| Stores both date and time | '2025-02-02 14:30:00' | |
TIMESTAMP
| Stores date & time (used for logging) | '2025-02-02 14:30:00' | πΉ Example: If youβre storing a studentβs birth date, use
DATE
. If youβre storing when a student logged in, use DATETIME
. ---
π Creating a Table in SQL
Now that we understand data types, letβs create a table for our students.
CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT,
Grade CHAR(1),
Enrollment_Date DATE
);
πΉ Explanation:
-
CREATE TABLE Students
β Creates a table named Students -
Student_ID INT PRIMARY KEY
β Unique ID for each student -
Name VARCHAR(50)
β Stores student names (up to 50 characters) -
Age INT
β Stores student ages -
Grade CHAR(1)
β Stores single-character grades (A, B, C...) -
Enrollment_Date DATE
β Stores the date of enrollment ---
π Writing Basic SQL Queries
Now, letβs insert some data and retrieve it using SQL queries.
1οΈβ£ Inserting Data into a Table
INSERT INTO Students (Student_ID, Name, Age, Grade, Enrollment_Date)
VALUES (1, 'John Doe', 18, 'A', '2023-09-01');
πΉ Explanation:
-
INSERT INTO Students
β Adds a new record to the Students table -
(Student_ID, Name, Age, Grade, Enrollment_Date)
β Specifies the columns -
VALUES (1, 'John Doe', 18, 'A', '2023-09-01')
β Provides the values Now, letβs add a few more students:
INSERT INTO Students (Student_ID, Name, Age, Grade, Enrollment_Date)
VALUES
(2, 'Emma Smith', 19, 'B', '2022-08-15'),
(3, 'Alex Brown', 20, 'A', '2021-07-10'),
(4, 'Sophia Johnson', 18, 'C', '2023-01-20');
---
2οΈβ£ Retrieving Data Using `SELECT` Statement
To see all student records, use:
SELECT * FROM Students;
πΉ Explanation:
-
SELECT *
β Selects all columns -
FROM Students
β Specifies the Students table πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
---
π5β€1
3οΈβ£ Retrieving Specific Columns
If you only want to see the Name and Age, run:
πΉ Output:
| Name | Age |
|--------------|----|
| John Doe | 18 |
| Emma Smith | 19 |
| Alex Brown | 20 |
| Sophia Johnson| 18 |
---
4οΈβ£ Filtering Data Using `WHERE` Clause
Find students who are 18 years old:
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
---
5οΈβ£ Using Conditions (`AND`, `OR`)
Find students who are 18 years old and have Grade A:
Find students who are either 18 or 19 years old:
---
π― Task for Today
1οΈβ£ Understand SQL data types and their usage.
2οΈβ£ Create a Students table in an SQL editor.
3οΈβ£ Insert at least 5 records into your table.
4οΈβ£ Write `SELECT` queries to retrieve:
β All students
β Students aged 18
β Only Name and Age
---
π Thatβs it for Day 2! Tomorrow, weβll learn about the WHERE clause and logical operators for filtering data efficiently. π
π‘ Like & comment if you're excited for Day 3! πβ€οΈ
If you only want to see the Name and Age, run:
SELECT Name, Age FROM Students;
πΉ Output:
| Name | Age |
|--------------|----|
| John Doe | 18 |
| Emma Smith | 19 |
| Alex Brown | 20 |
| Sophia Johnson| 18 |
---
4οΈβ£ Filtering Data Using `WHERE` Clause
Find students who are 18 years old:
SELECT * FROM Students WHERE Age = 18;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
---
5οΈβ£ Using Conditions (`AND`, `OR`)
Find students who are 18 years old and have Grade A:
SELECT * FROM Students WHERE Age = 18 AND Grade = 'A';
Find students who are either 18 or 19 years old:
SELECT * FROM Students WHERE Age = 18 OR Age = 19;
---
π― Task for Today
1οΈβ£ Understand SQL data types and their usage.
2οΈβ£ Create a Students table in an SQL editor.
3οΈβ£ Insert at least 5 records into your table.
4οΈβ£ Write `SELECT` queries to retrieve:
β All students
β Students aged 18
β Only Name and Age
---
π Thatβs it for Day 2! Tomorrow, weβll learn about the WHERE clause and logical operators for filtering data efficiently. π
π‘ Like & comment if you're excited for Day 3! πβ€οΈ
π4β€3
Day 3: Filtering Data Using the `WHERE` Clause and Logical Operators (`AND`, `OR`, `NOT`)
Welcome to Day 3 of your SQL journey! π
Yesterday, we learned about SQL data types and basic queries using `SELECT`. Today, we will take it further and learn how to filter data using the
By the end of this lesson, youβll be able to retrieve specific data based on conditions! π
---
π What is the `WHERE` Clause?
In real-world databases, tables contain thousands or even millions of records. If you only want to find specific data, you need a filtering method.
The
π Syntax:
---
π Using `WHERE` to Filter Data
Letβs take an example. We have a Students table with the following records:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
---
1οΈβ£ Filtering Data with `WHERE` Clause
Example 1: Find all students who are 18 years old
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
β Explanation:
- The query only selects students where
---
2οΈβ£ Using `AND` Operator
The `AND` operator allows us to filter based on multiple conditions.
Example 2: Find students who are 18 years old AND have Grade A
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
β Explanation:
- The query filters students who are both 18 years old AND have Grade A.
---
3οΈβ£ Using `OR` Operator
The `OR` operator allows us to filter if at least one condition is met.
Example 3: Find students who are either 18 OR 19 years old
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
β Explanation:
- The query selects students who are either 18 OR 19 years old.
---
4οΈβ£ Using `NOT` Operator
The `NOT` operator helps us find records that do NOT match a certain condition.
Example 4: Find students who are NOT 18 years old
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|-----------|-----|-------|----------------|
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- The query excludes students who are 18 years old.
---
π Combining `AND`, `OR`, and `NOT`
Example 5: Find students who are either Grade A OR Grade B, but NOT 18 years old
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|-----------|-----|-------|----------------|
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- The query selects students who have Grade A OR B.
- But it excludes students who are 18 years old.
---
π Using Comparison Operators with `WHERE`
Welcome to Day 3 of your SQL journey! π
Yesterday, we learned about SQL data types and basic queries using `SELECT`. Today, we will take it further and learn how to filter data using the
WHERE
clause and logical operators (AND
, OR
, NOT
). By the end of this lesson, youβll be able to retrieve specific data based on conditions! π
---
π What is the `WHERE` Clause?
In real-world databases, tables contain thousands or even millions of records. If you only want to find specific data, you need a filtering method.
The
WHERE
clause allows us to retrieve only the records that match certain conditions instead of displaying the entire table. π Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
---
π Using `WHERE` to Filter Data
Letβs take an example. We have a Students table with the following records:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
---
1οΈβ£ Filtering Data with `WHERE` Clause
Example 1: Find all students who are 18 years old
SELECT * FROM Students WHERE Age = 18;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
β Explanation:
- The query only selects students where
Age = 18
. ---
2οΈβ£ Using `AND` Operator
The `AND` operator allows us to filter based on multiple conditions.
Example 2: Find students who are 18 years old AND have Grade A
SELECT * FROM Students WHERE Age = 18 AND Grade = 'A';
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
β Explanation:
- The query filters students who are both 18 years old AND have Grade A.
---
3οΈβ£ Using `OR` Operator
The `OR` operator allows us to filter if at least one condition is met.
Example 3: Find students who are either 18 OR 19 years old
SELECT * FROM Students WHERE Age = 18 OR Age = 19;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
β Explanation:
- The query selects students who are either 18 OR 19 years old.
---
4οΈβ£ Using `NOT` Operator
The `NOT` operator helps us find records that do NOT match a certain condition.
Example 4: Find students who are NOT 18 years old
SELECT * FROM Students WHERE NOT Age = 18;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|-----------|-----|-------|----------------|
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- The query excludes students who are 18 years old.
---
π Combining `AND`, `OR`, and `NOT`
Example 5: Find students who are either Grade A OR Grade B, but NOT 18 years old
SELECT * FROM Students WHERE (Grade = 'A' OR Grade = 'B') AND NOT Age = 18;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|-----------|-----|-------|----------------|
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- The query selects students who have Grade A OR B.
- But it excludes students who are 18 years old.
---
π Using Comparison Operators with `WHERE`
π2β€1
| Operator | Meaning |
|----------|---------|
|
|
|
|
|
|
Example 6: Find students older than 18 years
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|-----------|-----|-------|----------------|
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- The query selects students who are older than 18.
---
## π― Task for Today
β Write a query to find students who are exactly 19 years old.
β Write a query to find students who are younger than 19.
β Write a query to find students who are either 18 OR 20 years old.
β Write a query to find students who are not Grade A.
β Write a query to find students who are older than 18 AND have Grade B.
---
π Summary
β
β
β
β
β We can combine multiple conditions using
---
π Thatβs it for Day 3! Tomorrow, weβll learn about sorting data using `ORDER BY`, limiting results with `LIMIT`, and removing duplicates using `DISTINCT`. π
Share with Credit: https://t.me/codingdidi
π‘ Like & comment if you're excited for Day 4! πβ€οΈ
|----------|---------|
|
=
| Equals ||
!=
or <>
| Not Equal ||
>
| Greater than ||
<
| Less than ||
>=
| Greater than or equal to ||
<=
| Less than or equal to |Example 6: Find students older than 18 years
SELECT * FROM Students WHERE Age > 18;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|-----------|-----|-------|----------------|
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- The query selects students who are older than 18.
---
## π― Task for Today
β Write a query to find students who are exactly 19 years old.
β Write a query to find students who are younger than 19.
β Write a query to find students who are either 18 OR 20 years old.
β Write a query to find students who are not Grade A.
β Write a query to find students who are older than 18 AND have Grade B.
---
π Summary
β
WHERE
filters records based on a condition. β
AND
requires both conditions to be met. β
OR
requires at least one condition to be met. β
NOT
excludes specific records. β We can combine multiple conditions using
AND
, OR
, and NOT
. ---
π Thatβs it for Day 3! Tomorrow, weβll learn about sorting data using `ORDER BY`, limiting results with `LIMIT`, and removing duplicates using `DISTINCT`. π
Share with Credit: https://t.me/codingdidi
π‘ Like & comment if you're excited for Day 4! πβ€οΈ
Telegram
@Codingdidi
Free learning Resources For Data Analysts, Data science, ML, AI, GEN AI and Job updates, career growth, Tech updates
π4
This is how you can learn everything:
1. 25 minutes of focused learning
2. 5 minutes break
3. 25 minutes of focused learning
4. 25 minutes break minimum
5. Optionally go back to step 1
You can complete this cycle 2 times max per day, and it works wonders.
1. 25 minutes of focused learning
2. 5 minutes break
3. 25 minutes of focused learning
4. 25 minutes break minimum
5. Optionally go back to step 1
You can complete this cycle 2 times max per day, and it works wonders.
π4π₯1
Hi, all
Your inputs are helping me make this SQL series more informative.
Do comments your inputs. β
Happy Learning π
Your inputs are helping me make this SQL series more informative.
Do comments your inputs. β
Happy Learning π
Day 4: Sorting Data (`ORDER BY`), Limiting Results (`LIMIT`, `OFFSET`), and Removing Duplicates (`DISTINCT`)
Welcome to Day 4 of learning SQL! π
Yesterday, we learned how to filter data using `WHERE` and logical operators (
β Sort data using `ORDER BY`
β Limit the number of results using `LIMIT` and `OFFSET`
β Remove duplicate values using `DISTINCT`
By the end of this lesson, youβll be able to organize and refine your query results efficiently! π
---
π Sorting Data Using `ORDER BY`
πΉ Why Do We Need Sorting?
When you query a table, the results might appear in random order. If you want your data to be more organized and meaningful, you need to sort it based on a specific column.
π Syntax:
-
-
---
1οΈβ£ Sorting in Ascending Order (`ASC`)
Letβs use a Students table as an example:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
Example 1: Sort students by Age (Ascending)
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- The records are sorted from youngest (18) to oldest (20).
---
2οΈβ£ Sorting in Descending Order (`DESC`)
Example 2: Sort students by Age (Descending)
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 3 | Alex Brown | 20 | A | 2021-07-10 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 1 | John Doe | 18 | A | 2023-09-01 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
β Explanation:
- The records are sorted from oldest (20) to youngest (18).
---
3οΈβ£ Sorting by Multiple Columns
If two students have the same age, you can sort further by another column, like Grade.
Example 3: Sort students by Age (Ascending), then by Grade (Ascending)
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- Students are sorted by Age (smallest first).
- If two students have the same age, they are sorted by Grade (A before C).
---
π Limiting Results Using `LIMIT` and `OFFSET`
πΉ Why Do We Need `LIMIT`?
Imagine you have 1 million records, but you only need to see the top 5 results. The
π Syntax:
Example 4: Get the Top 3 Youngest Students
Welcome to Day 4 of learning SQL! π
Yesterday, we learned how to filter data using `WHERE` and logical operators (
AND
, OR
, NOT
). Today, weβll take it a step further and learn how to: β Sort data using `ORDER BY`
β Limit the number of results using `LIMIT` and `OFFSET`
β Remove duplicate values using `DISTINCT`
By the end of this lesson, youβll be able to organize and refine your query results efficiently! π
---
π Sorting Data Using `ORDER BY`
πΉ Why Do We Need Sorting?
When you query a table, the results might appear in random order. If you want your data to be more organized and meaningful, you need to sort it based on a specific column.
π Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column_name ASC/DESC;
-
ASC
(Ascending Order) β Default, sorts from smallest to largest (A-Z, 0-9). -
DESC
(Descending Order) β Sorts from largest to smallest (Z-A, 9-0). ---
1οΈβ£ Sorting in Ascending Order (`ASC`)
Letβs use a Students table as an example:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
Example 1: Sort students by Age (Ascending)
SELECT * FROM Students ORDER BY Age ASC;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- The records are sorted from youngest (18) to oldest (20).
---
2οΈβ£ Sorting in Descending Order (`DESC`)
Example 2: Sort students by Age (Descending)
SELECT * FROM Students ORDER BY Age DESC;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 3 | Alex Brown | 20 | A | 2021-07-10 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 1 | John Doe | 18 | A | 2023-09-01 |
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
β Explanation:
- The records are sorted from oldest (20) to youngest (18).
---
3οΈβ£ Sorting by Multiple Columns
If two students have the same age, you can sort further by another column, like Grade.
Example 3: Sort students by Age (Ascending), then by Grade (Ascending)
SELECT * FROM Students ORDER BY Age ASC, Grade ASC;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
| 3 | Alex Brown | 20 | A | 2021-07-10 |
β Explanation:
- Students are sorted by Age (smallest first).
- If two students have the same age, they are sorted by Grade (A before C).
---
π Limiting Results Using `LIMIT` and `OFFSET`
πΉ Why Do We Need `LIMIT`?
Imagine you have 1 million records, but you only need to see the top 5 results. The
LIMIT
clause helps restrict the number of rows returned by a query. π Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column_name
LIMIT number;
Example 4: Get the Top 3 Youngest Students
SELECT * FROM Students ORDER BY Age ASC LIMIT 3;
π1
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
β Explanation:
- We only get 3 results instead of the full table.
---
π Skipping Rows Using `OFFSET`
π Syntax:
Example 5: Get the second and third youngest students (Skip the first one)
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|-----------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith| 19 | B | 2022-08-15 |
β Explanation:
- The first student (
---
π Removing Duplicates Using `DISTINCT`
πΉ Why Do We Need `DISTINCT`?
Sometimes, a column contains repeated values, and you only need unique values.
π Syntax:
Example 6: Get All Unique Grades
πΉ Output:
| Grade |
|-------|
| A |
| B |
| C |
β Explanation:
- The query removes duplicate values from the Grade column.
---
π― Task for Today
β Write a query to get the top 5 oldest students.
β Write a query to list unique enrollment dates.
β Write a query to get the second highest age student.
---
π Summary
β
β
β
β
Tomorrow, we will learn SQL Aggregate Functions (`COUNT`, `SUM`, `AVG`, `MIN`, `MAX`). π
Share with Credit: https://t.me/codingdidi
π‘ Like & Comment if you're ready for Day 5! πβ€οΈ
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|--------------|-----|-------|----------------|
| 4 | Sophia Johnson| 18 | C | 2023-01-20 |
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith | 19 | B | 2022-08-15 |
β Explanation:
- We only get 3 results instead of the full table.
---
π Skipping Rows Using `OFFSET`
OFFSET
is used with `LIMIT` to skip a specific number of rows before returning results. π Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column_name
LIMIT number OFFSET number;
Example 5: Get the second and third youngest students (Skip the first one)
SELECT * FROM Students ORDER BY Age ASC LIMIT 2 OFFSET 1;
πΉ Output:
| Student_ID | Name | Age | Grade | Enrollment_Date |
|------------|-----------|-----|-------|----------------|
| 1 | John Doe | 18 | A | 2023-09-01 |
| 2 | Emma Smith| 19 | B | 2022-08-15 |
β Explanation:
- The first student (
Sophia Johnson, Age 18
) is skipped, and the next 2 students are returned. ---
π Removing Duplicates Using `DISTINCT`
πΉ Why Do We Need `DISTINCT`?
Sometimes, a column contains repeated values, and you only need unique values.
π Syntax:
SELECT DISTINCT column_name FROM table_name;
Example 6: Get All Unique Grades
SELECT DISTINCT Grade FROM Students;
πΉ Output:
| Grade |
|-------|
| A |
| B |
| C |
β Explanation:
- The query removes duplicate values from the Grade column.
---
π― Task for Today
β Write a query to get the top 5 oldest students.
β Write a query to list unique enrollment dates.
β Write a query to get the second highest age student.
---
π Summary
β
ORDER BY
sorts data (Ascending/Descending). β
LIMIT
restricts the number of rows returned. β
OFFSET
skips a specific number of rows. β
DISTINCT
removes duplicate values. Tomorrow, we will learn SQL Aggregate Functions (`COUNT`, `SUM`, `AVG`, `MIN`, `MAX`). π
Share with Credit: https://t.me/codingdidi
π‘ Like & Comment if you're ready for Day 5! πβ€οΈ
Telegram
@Codingdidi
Free learning Resources For Data Analysts, Data science, ML, AI, GEN AI and Job updates, career growth, Tech updates
π6
Day 5: SQL Aggregate Functions (`COUNT`, `SUM`, `AVG`, `MIN`, `MAX`)
Welcome to Day 5 of learning SQL! π
So far, weβve learned how to filter, sort, limit, and remove duplicates in our SQL queries. Today, we will take it one step further by learning Aggregate Functions in SQL.
πΉ What Are Aggregate Functions?
Aggregate functions perform calculations on a group of rows and return a single value. These functions are useful when we want to summarize data, such as:
β Counting the number of records (
β Finding the total sum (
β Calculating the average (
β Finding the minimum value (
β Finding the maximum value (
Letβs go step by step! π
---
π `COUNT()` β Counting the Number of Rows
πΉ Why Do We Need `COUNT()`?
We use
π Syntax:
-
-
---
Example 1: Count the Total Number of Students
Consider this Students table:
| Student_ID | Name | Age | Grade | Fees_Paid |
|------------|---------------|-----|-------|----------|
| 1 | John Doe | 18 | A | 1000 |
| 2 | Emma Smith | 19 | B | 1200 |
| 3 | Alex Brown | 20 | A | 900 |
| 4 | Sophia Johnson | 18 | C | NULL |
πΉ Output:
| COUNT(*) |
|----------|
| 4 |
β Explanation:
- This query counts all rows in the table.
---
Example 2: Count the Number of Students Who Paid Fees
πΉ Output:
| COUNT(Fees_Paid) |
|------------------|
| 3 |
β Explanation:
- This query excludes NULL values in
---
π `SUM()` β Adding Up Values
πΉ Why Do We Need `SUM()`?
π Syntax:
---
Example 3: Find the Total Fees Paid
πΉ Output:
| SUM(Fees_Paid) |
|---------------|
| 3100 |
β Explanation:
- The sum of 1000 + 1200 + 900 is 3100 (ignores NULL values).
---
π `AVG()` β Finding the Average
πΉ Why Do We Need `AVG()`?
π Syntax:
---
Example 4: Find the Average Fees Paid
πΉ Output:
| AVG(Fees_Paid) |
|---------------|
| 1033.33 |
β Explanation:
- The average is (1000 + 1200 + 900) Γ· 3 = 1033.33 (ignores NULL values).
---
π `MIN()` β Finding the Minimum Value
πΉ Why Do We Need `MIN()`?
π Syntax:
---
Example 5: Find the Youngest Studentβs Age
πΉ Output:
| MIN(Age) |
|---------|
| 18 |
β Explanation:
- The minimum age in the table is 18.
---
π `MAX()` β Finding the Maximum Value
πΉ Why Do We Need `MAX()`?
π Syntax:
---
Example 6: Find the Oldest Studentβs Age
πΉ Output:
| MAX(Age) |
|---------|
| 20 |
β Explanation:
- The maximum age in the table is 20.
---
π Combining Aggregate Functions
We can use multiple aggregate functions in a single query.
Example 7: Get All Summary Data
πΉ Output:
| Total_Students | Total_Fees | Average_Fees | Youngest_Age | Oldest_Age |
|---------------|-----------|-------------|-------------|-----------|
| 4 | 3100 | 1033.33 | 18 | 20 |
β Explanation:
- This query provides a complete summary of the student data.
---
Welcome to Day 5 of learning SQL! π
So far, weβve learned how to filter, sort, limit, and remove duplicates in our SQL queries. Today, we will take it one step further by learning Aggregate Functions in SQL.
πΉ What Are Aggregate Functions?
Aggregate functions perform calculations on a group of rows and return a single value. These functions are useful when we want to summarize data, such as:
β Counting the number of records (
COUNT
) β Finding the total sum (
SUM
) β Calculating the average (
AVG
) β Finding the minimum value (
MIN
) β Finding the maximum value (
MAX
) Letβs go step by step! π
---
π `COUNT()` β Counting the Number of Rows
πΉ Why Do We Need `COUNT()`?
We use
COUNT()
to find how many rows exist in a table or how many times a specific value appears. π Syntax:
SELECT COUNT(column_name) FROM table_name;
-
COUNT(column_name)
: Counts non-null values in a specific column. -
COUNT(*)
: Counts all rows, including those with NULL values. ---
Example 1: Count the Total Number of Students
Consider this Students table:
| Student_ID | Name | Age | Grade | Fees_Paid |
|------------|---------------|-----|-------|----------|
| 1 | John Doe | 18 | A | 1000 |
| 2 | Emma Smith | 19 | B | 1200 |
| 3 | Alex Brown | 20 | A | 900 |
| 4 | Sophia Johnson | 18 | C | NULL |
SELECT COUNT(*) FROM Students;
πΉ Output:
| COUNT(*) |
|----------|
| 4 |
β Explanation:
- This query counts all rows in the table.
---
Example 2: Count the Number of Students Who Paid Fees
SELECT COUNT(Fees_Paid) FROM Students;
πΉ Output:
| COUNT(Fees_Paid) |
|------------------|
| 3 |
β Explanation:
- This query excludes NULL values in
Fees_Paid
. ---
π `SUM()` β Adding Up Values
πΉ Why Do We Need `SUM()`?
SUM()
calculates the total sum of numeric values in a column. π Syntax:
SELECT SUM(column_name) FROM table_name;
---
Example 3: Find the Total Fees Paid
SELECT SUM(Fees_Paid) FROM Students;
πΉ Output:
| SUM(Fees_Paid) |
|---------------|
| 3100 |
β Explanation:
- The sum of 1000 + 1200 + 900 is 3100 (ignores NULL values).
---
π `AVG()` β Finding the Average
πΉ Why Do We Need `AVG()`?
AVG()
calculates the average (mean) value of a numeric column. π Syntax:
SELECT AVG(column_name) FROM table_name;
---
Example 4: Find the Average Fees Paid
SELECT AVG(Fees_Paid) FROM Students;
πΉ Output:
| AVG(Fees_Paid) |
|---------------|
| 1033.33 |
β Explanation:
- The average is (1000 + 1200 + 900) Γ· 3 = 1033.33 (ignores NULL values).
---
π `MIN()` β Finding the Minimum Value
πΉ Why Do We Need `MIN()`?
MIN()
returns the smallest value in a column. π Syntax:
SELECT MIN(column_name) FROM table_name;
---
Example 5: Find the Youngest Studentβs Age
SELECT MIN(Age) FROM Students;
πΉ Output:
| MIN(Age) |
|---------|
| 18 |
β Explanation:
- The minimum age in the table is 18.
---
π `MAX()` β Finding the Maximum Value
πΉ Why Do We Need `MAX()`?
MAX()
returns the largest value in a column. π Syntax:
SELECT MAX(column_name) FROM table_name;
---
Example 6: Find the Oldest Studentβs Age
SELECT MAX(Age) FROM Students;
πΉ Output:
| MAX(Age) |
|---------|
| 20 |
β Explanation:
- The maximum age in the table is 20.
---
π Combining Aggregate Functions
We can use multiple aggregate functions in a single query.
Example 7: Get All Summary Data
SELECT
COUNT(*) AS Total_Students,
SUM(Fees_Paid) AS Total_Fees,
AVG(Fees_Paid) AS Average_Fees,
MIN(Age) AS Youngest_Age,
MAX(Age) AS Oldest_Age
FROM Students;
πΉ Output:
| Total_Students | Total_Fees | Average_Fees | Youngest_Age | Oldest_Age |
|---------------|-----------|-------------|-------------|-----------|
| 4 | 3100 | 1033.33 | 18 | 20 |
β Explanation:
- This query provides a complete summary of the student data.
---
β€1
π― Task for Today
β Count the number of students in Grade A.
β Find the total fees paid by students in Grade B.
β Get the average age of students.
β Find the highest and lowest fees paid.
---
π Summary
β
β
β
β
β
Tomorrow, we will learn about SQL GROUP BY & HAVING. π
Share with Credit: https://t.me/codingdidi
π‘ Like & Comment if you're ready for Day 6! πβ€οΈ
β Count the number of students in Grade A.
β Find the total fees paid by students in Grade B.
β Get the average age of students.
β Find the highest and lowest fees paid.
---
π Summary
β
COUNT()
β Counts the number of rows. β
SUM()
β Adds up values. β
AVG()
β Finds the average. β
MIN()
β Finds the smallest value. β
MAX()
β Finds the largest value. Tomorrow, we will learn about SQL GROUP BY & HAVING. π
Share with Credit: https://t.me/codingdidi
π‘ Like & Comment if you're ready for Day 6! πβ€οΈ
Telegram
@Codingdidi
Free learning Resources For Data Analysts, Data science, ML, AI, GEN AI and Job updates, career growth, Tech updates
π4
Day 6: SQL `GROUP BY` and `HAVING` β Grouping and Filtering Data
Welcome to Day 6 of learning SQL! π
Yesterday, we learned about aggregate functions (
For example, instead of finding the total fees paid by all students, what if we want to find the total fees paid per grade? Thatβs where
---
πΉ Why Do We Need `GROUP BY`?
π Syntax:
-
-
---
π `GROUP BY` Example β Total Fees Paid Per Grade
We will use the same Students table:
| Student_ID | Name | Age | Grade | Fees_Paid |
|------------|---------------|-----|-------|----------|
| 1 | John Doe | 18 | A | 1000 |
| 2 | Emma Smith | 19 | B | 1200 |
| 3 | Alex Brown | 20 | A | 900 |
| 4 | Sophia Johnson | 18 | C | NULL |
| 5 | Liam Davis | 19 | B | 1100 |
---
πΈ Find the Total Fees Paid Per Grade
πΉ Output:
| Grade | Total_Fees |
|-------|-----------|
| A | 1900 |
| B | 2300 |
| C | NULL |
β Explanation:
- The query groups students by Grade.
- Then it calculates the total fees paid for each grade using
- Grade C shows NULL because Sophia hasn't paid fees (NULL values are ignored in
---
πΈ Count the Number of Students in Each Grade
πΉ Output:
| Grade | Total_Students |
|-------|---------------|
| A | 2 |
| B | 2 |
| C | 1 |
β Explanation:
-
-
---
π `HAVING` Clause β Filtering Groups
The
π¨ Use `HAVING` to filter groups after aggregation!
π Syntax:
---
πΈ Find Grades Where Total Fees Paid is More Than 2000
πΉ Output:
| Grade | Total_Fees |
|-------|-----------|
| B | 2300 |
β Explanation:
- The query groups students by Grade and calculates total fees per grade.
-
- Grade A (1900) is excluded, but Grade B (2300) is included.
---
πΈ Find Grades with More Than 1 Student
πΉ Output:
| Grade | Total_Students |
|-------|---------------|
| A | 2 |
| B | 2 |
β Explanation:
-
-
---
π `WHERE` vs. `HAVING` β Key Differences
| Feature |
|----------|--------|---------|
| Filters individual rows before grouping | β Yes | β No |
| Filters groups after aggregation | β No | β Yes |
| Works with aggregate functions (
---
π― Task for Today
β Find the total fees paid per grade but only show grades where fees are above 2000.
β Count the number of students per age and show only ages where students are more than 1.
β Find the average fees per grade and show only grades where the average fee is above 1000.
---
Welcome to Day 6 of learning SQL! π
Yesterday, we learned about aggregate functions (
COUNT
, SUM
, AVG
, MIN
, MAX
) to summarize data. But what if we want to apply these functions to different groups of data? π€ For example, instead of finding the total fees paid by all students, what if we want to find the total fees paid per grade? Thatβs where
GROUP BY
comes in! π ---
πΉ Why Do We Need `GROUP BY`?
GROUP BY
helps us group rows with the same values in a column and then apply aggregate functions to each group separately. π Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name;
-
column_name
β The column used for grouping. -
aggregate_function(column_name)
β Applies an aggregate function (e.g., SUM
, AVG
, COUNT
, etc.) to each group. ---
π `GROUP BY` Example β Total Fees Paid Per Grade
We will use the same Students table:
| Student_ID | Name | Age | Grade | Fees_Paid |
|------------|---------------|-----|-------|----------|
| 1 | John Doe | 18 | A | 1000 |
| 2 | Emma Smith | 19 | B | 1200 |
| 3 | Alex Brown | 20 | A | 900 |
| 4 | Sophia Johnson | 18 | C | NULL |
| 5 | Liam Davis | 19 | B | 1100 |
---
πΈ Find the Total Fees Paid Per Grade
SELECT Grade, SUM(Fees_Paid) AS Total_Fees
FROM Students
GROUP BY Grade;
πΉ Output:
| Grade | Total_Fees |
|-------|-----------|
| A | 1900 |
| B | 2300 |
| C | NULL |
β Explanation:
- The query groups students by Grade.
- Then it calculates the total fees paid for each grade using
SUM(Fees_Paid)
. - Grade C shows NULL because Sophia hasn't paid fees (NULL values are ignored in
SUM()
). ---
πΈ Count the Number of Students in Each Grade
SELECT Grade, COUNT(*) AS Total_Students
FROM Students
GROUP BY Grade;
πΉ Output:
| Grade | Total_Students |
|-------|---------------|
| A | 2 |
| B | 2 |
| C | 1 |
β Explanation:
-
COUNT(*)
counts all students in each grade. -
GROUP BY Grade
groups them by grade before counting. ---
π `HAVING` Clause β Filtering Groups
The
WHERE
clause cannot be used with aggregate functions because it filters individual rows before grouping. π¨ Use `HAVING` to filter groups after aggregation!
π Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
---
πΈ Find Grades Where Total Fees Paid is More Than 2000
SELECT Grade, SUM(Fees_Paid) AS Total_Fees
FROM Students
GROUP BY Grade
HAVING SUM(Fees_Paid) > 2000;
πΉ Output:
| Grade | Total_Fees |
|-------|-----------|
| B | 2300 |
β Explanation:
- The query groups students by Grade and calculates total fees per grade.
-
HAVING SUM(Fees_Paid) > 2000
filters only groups where the total fees paid exceeds 2000. - Grade A (1900) is excluded, but Grade B (2300) is included.
---
πΈ Find Grades with More Than 1 Student
SELECT Grade, COUNT(*) AS Total_Students
FROM Students
GROUP BY Grade
HAVING COUNT(*) > 1;
πΉ Output:
| Grade | Total_Students |
|-------|---------------|
| A | 2 |
| B | 2 |
β Explanation:
-
COUNT(*)
counts the number of students per grade. -
HAVING COUNT(*) > 1
filters out grades that have only 1 student (Grade C). ---
π `WHERE` vs. `HAVING` β Key Differences
| Feature |
WHERE
| HAVING
||----------|--------|---------|
| Filters individual rows before grouping | β Yes | β No |
| Filters groups after aggregation | β No | β Yes |
| Works with aggregate functions (
SUM
, COUNT
, etc.) | β No | β
Yes |---
π― Task for Today
β Find the total fees paid per grade but only show grades where fees are above 2000.
β Count the number of students per age and show only ages where students are more than 1.
β Find the average fees per grade and show only grades where the average fee is above 1000.
---
β€4π3
π Summary
β
β Aggregate functions (
β
β
Tomorrow, we will learn about SQL Joins (INNER JOIN, LEFT JOIN, etc.) to combine data from multiple tables! π
π‘ Like & Comment if you're ready for Day 7! πβ€οΈ
β
GROUP BY
β Groups rows by a column. β Aggregate functions (
SUM
, AVG
, COUNT
, etc.) summarize each group. β
HAVING
filters groups after aggregation. β
WHERE
filters before grouping. Tomorrow, we will learn about SQL Joins (INNER JOIN, LEFT JOIN, etc.) to combine data from multiple tables! π
π‘ Like & Comment if you're ready for Day 7! πβ€οΈ
Day 7: SQL Hands-On Practice β Strengthening Your Basics π―
Congratulations! π You've completed the first 6 days of SQL learning! Now, before moving forward to more complex topics, it's important to review, practice, and solidify what we've learned so far.
Today, we will:
βοΈ Revise the key SQL concepts covered this week.
βοΈ Practice with real SQL queries.
βοΈ Solve challenges on SQL platforms like HackerRank, LeetCode, and W3Schools.
---
π Quick Revision of Week 1 Topics
Letβs quickly go over what we learned in the past 6 days.
πΉ Day 1: Introduction to SQL & Databases
- SQL (Structured Query Language) is used to store, retrieve, and manage data in databases.
- Popular database systems: MySQL, PostgreSQL, SQL Server.
- SQL operates on tables that store data in rows and columns.
πΉ Day 2: SQL Data Types & Basic Queries
- SQL supports different data types:
-
-
-
-
- Basic queries:
-
-
πΉ Day 3: Filtering Data with `WHERE`
- The
- Comparison operators:
- Logical operators:
Filters students where `Age` is greater than 18.
πΉ Day 4: Sorting & Limiting Data
-
-
-
πΉ Finds the top 3 students with the highest grades.
πΉ Day 5: Aggregate Functions
-
πΉ Counts how many students got Grade A.
πΉ Day 6: Grouping Data with `GROUP BY` & `HAVING`
-
-
πΉ Finds grades where the average fees paid is greater than 1000.
---
π― Hands-On Practice: Solve These SQL Problems
Problem 1: Find the Total Fees Paid by Each Grade
πΉ Expected Output:
| Grade | Total_Fees |
|-------|-----------|
| A | 1900 |
| B | 2300 |
| C | NULL |
Task: Run this query and check if your database returns the correct results.
---
Problem 2: List Students Who Are 18 Years or Older
Expected Output: All students aged 18 or older.
---
Problem 3: Count How Many Students Are in Each Grade
Expected Output:
| Grade | Student_Count |
|-------|--------------|
| A | 2 |
| B | 2 |
| C | 1 |
---
Problem 4: Get the Top 2 Youngest Students
Expected Output: The 2 youngest students.
---
Problem 5: Find the Maximum Fees Paid by Any Student
πΉ Expected Output: The highest fee paid.
---
π Platforms to Practice SQL
If you donβt have SQL installed, you can practice online for free on these platforms:
| Platform | Features |
|--------------|-------------|
| [HackerRank](https://www.hackerrank.com/domains/sql) | Beginner to advanced SQL challenges |
| [LeetCode SQL](https://leetcode.com/problemset/database/) | Real-world SQL interview questions |
| [W3Schools SQL](https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all) | Interactive SQL editor |
---
π Your Tasks for Today
β Revise all SQL topics from Day 1 β Day 6.
β Write and run the 5 practice queries above.
β Solve at least 3 SQL challenges on HackerRank, LeetCode, or W3Schools.
β Comment "Done β " if you've completed today's tasks!
Congratulations! π You've completed the first 6 days of SQL learning! Now, before moving forward to more complex topics, it's important to review, practice, and solidify what we've learned so far.
Today, we will:
βοΈ Revise the key SQL concepts covered this week.
βοΈ Practice with real SQL queries.
βοΈ Solve challenges on SQL platforms like HackerRank, LeetCode, and W3Schools.
---
π Quick Revision of Week 1 Topics
Letβs quickly go over what we learned in the past 6 days.
πΉ Day 1: Introduction to SQL & Databases
- SQL (Structured Query Language) is used to store, retrieve, and manage data in databases.
- Popular database systems: MySQL, PostgreSQL, SQL Server.
- SQL operates on tables that store data in rows and columns.
πΉ Day 2: SQL Data Types & Basic Queries
- SQL supports different data types:
-
INT
(integer numbers) -
VARCHAR(n)
(text) -
DATE
(dates) -
DECIMAL(p,s)
(for precise numbers like currency). - Basic queries:
SELECT column1, column2 FROM table_name;
-
SELECT
retrieves specific columns. -
FROM
specifies the table.πΉ Day 3: Filtering Data with `WHERE`
- The
WHERE
clause filters rows based on conditions.- Comparison operators:
=
, >
, <
, >=
, <=
, !=
- Logical operators:
AND
, OR
, NOT
SELECT * FROM Students WHERE Age > 18;
Filters students where `Age` is greater than 18.
πΉ Day 4: Sorting & Limiting Data
-
ORDER BY
sorts data in ascending (`ASC`) or descending (`DESC`) order.-
LIMIT
restricts the number of rows.-
DISTINCT
removes duplicates.SELECT Name, Grade FROM Students ORDER BY Grade DESC LIMIT 3;
πΉ Finds the top 3 students with the highest grades.
πΉ Day 5: Aggregate Functions
-
COUNT()
, SUM()
, AVG()
, MIN()
, MAX()
summarize data.SELECT COUNT(*) FROM Students WHERE Grade = 'A';
πΉ Counts how many students got Grade A.
πΉ Day 6: Grouping Data with `GROUP BY` & `HAVING`
-
GROUP BY
groups rows based on a column.-
HAVING
filters groups (used instead of WHERE
for aggregated data).SELECT Grade, AVG(Fees_Paid) FROM Students GROUP BY Grade HAVING AVG(Fees_Paid) > 1000;
πΉ Finds grades where the average fees paid is greater than 1000.
---
π― Hands-On Practice: Solve These SQL Problems
Problem 1: Find the Total Fees Paid by Each Grade
SELECT Grade, SUM(Fees_Paid) AS Total_Fees
FROM Students
GROUP BY Grade;
πΉ Expected Output:
| Grade | Total_Fees |
|-------|-----------|
| A | 1900 |
| B | 2300 |
| C | NULL |
Task: Run this query and check if your database returns the correct results.
---
Problem 2: List Students Who Are 18 Years or Older
SELECT Name, Age FROM Students WHERE Age >= 18;
Expected Output: All students aged 18 or older.
---
Problem 3: Count How Many Students Are in Each Grade
SELECT Grade, COUNT(*) AS Student_Count
FROM Students
GROUP BY Grade;
Expected Output:
| Grade | Student_Count |
|-------|--------------|
| A | 2 |
| B | 2 |
| C | 1 |
---
Problem 4: Get the Top 2 Youngest Students
SELECT Name, Age FROM Students ORDER BY Age ASC LIMIT 2;
Expected Output: The 2 youngest students.
---
Problem 5: Find the Maximum Fees Paid by Any Student
SELECT MAX(Fees_Paid) AS Max_Fees FROM Students;
πΉ Expected Output: The highest fee paid.
---
π Platforms to Practice SQL
If you donβt have SQL installed, you can practice online for free on these platforms:
| Platform | Features |
|--------------|-------------|
| [HackerRank](https://www.hackerrank.com/domains/sql) | Beginner to advanced SQL challenges |
| [LeetCode SQL](https://leetcode.com/problemset/database/) | Real-world SQL interview questions |
| [W3Schools SQL](https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all) | Interactive SQL editor |
---
π Your Tasks for Today
β Revise all SQL topics from Day 1 β Day 6.
β Write and run the 5 practice queries above.
β Solve at least 3 SQL challenges on HackerRank, LeetCode, or W3Schools.
β Comment "Done β " if you've completed today's tasks!
π3
Tomorrow, we move on to SQL Joins (INNER JOIN, LEFT JOIN, etc.) β a crucial topic for combining multiple tables! π
Like β€οΈ and Share if you're excited for Day 8! π
Like β€οΈ and Share if you're excited for Day 8! π
HackerRank
Solve Programming Questions | HackerRank
A special-purpose language designed for managing data held in a relational database.
β€1
Day 8: SQL JOINS β Combining Data from Multiple Tables π
Welcome to Week 2 of your SQL journey! π
So far, we have learned how to retrieve, filter, sort, and aggregate data from a single table. But in real-world databases, data is stored across multiple tables to maintain efficiency and reduce redundancy.
π‘ How do we fetch related data from multiple tables?
π Using SQL JOINS!
Today, we will cover:
βοΈ What are JOINS?
βοΈ Types of JOINS (Focusing on INNER JOIN & LEFT JOIN today).
βοΈ Real-life examples with simple explanations.
βοΈ Hands-on SQL queries.
---
π What are SQL JOINS?
A JOIN is used to combine rows from two or more tables based on a related column.
Imagine you have:
- Students Table (Stores student details).
- Courses Table (Stores course details).
If you want to find which student is enrolled in which course, you need to JOIN these two tables on a common column (e.g.,
---
πΉ Types of SQL JOINS
1οΈβ£ INNER JOIN β Returns only matching records from both tables.
2οΈβ£ LEFT JOIN β Returns all records from the left table and matching records from the right table.
3οΈβ£ RIGHT JOIN β Returns all records from the right table and matching records from the left table.
4οΈβ£ FULL JOIN β Returns all records from both tables (matching and non-matching).
---
πΉ Understanding INNER JOIN (Most Common JOIN)
π― Example: Students and Courses
| Students Table | | Courses Table |
|------------------|-----------------|------------------|
| Student_ID | Name | Course_ID | Course_ID | Course_Name |
|-----------|--------|----------|----------|-------------|
| 1 | Alice | C101 | C101 | Python |
| 2 | Bob | C102 | C102 | SQL |
| 3 | Charlie| C103 | C103 | Power BI |
| 4 | David | NULL | | |
πΉ David has no course assigned (NULL value in Course_ID).
πΉ To get only students who are enrolled in a course, we use
πΉ Output:
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
π David is not included because he has no matching Course_ID.
---
πΉ Understanding LEFT JOIN
πΉ LEFT JOIN returns ALL records from the left table (Students) and matching records from the right table (Courses).
πΉ If there is no match, NULL is returned.
πΉ Output (Now including David too):
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| David | NULL |
π David is included, but Course_Name is NULL because there is no matching Course_ID.
---
π― Hands-On Practice: Solve These SQL Problems
1οΈβ£ Find all students who are enrolled in a course (Use
2οΈβ£ Find all students, even those without courses (Use
3οΈβ£ Find courses that have students enrolled (Use
π Your Tasks for Today
β Revise INNER JOIN & LEFT JOIN.
β Run the practice queries in SQL.
β Try at least 3 SQL JOIN problems on HackerRank or LeetCode.
β Comment "Done β " once you complete today's practice!
Tomorrow, weβll explore RIGHT JOIN, FULL JOIN, and SELF JOIN!
π Like β€οΈ and Share if youβre excited for Day 9! π
Welcome to Week 2 of your SQL journey! π
So far, we have learned how to retrieve, filter, sort, and aggregate data from a single table. But in real-world databases, data is stored across multiple tables to maintain efficiency and reduce redundancy.
π‘ How do we fetch related data from multiple tables?
π Using SQL JOINS!
Today, we will cover:
βοΈ What are JOINS?
βοΈ Types of JOINS (Focusing on INNER JOIN & LEFT JOIN today).
βοΈ Real-life examples with simple explanations.
βοΈ Hands-on SQL queries.
---
π What are SQL JOINS?
A JOIN is used to combine rows from two or more tables based on a related column.
Imagine you have:
- Students Table (Stores student details).
- Courses Table (Stores course details).
If you want to find which student is enrolled in which course, you need to JOIN these two tables on a common column (e.g.,
Student_ID
). ---
πΉ Types of SQL JOINS
1οΈβ£ INNER JOIN β Returns only matching records from both tables.
2οΈβ£ LEFT JOIN β Returns all records from the left table and matching records from the right table.
3οΈβ£ RIGHT JOIN β Returns all records from the right table and matching records from the left table.
4οΈβ£ FULL JOIN β Returns all records from both tables (matching and non-matching).
---
πΉ Understanding INNER JOIN (Most Common JOIN)
INNER JOIN
returns only the matching records from both tables. π― Example: Students and Courses
| Students Table | | Courses Table |
|------------------|-----------------|------------------|
| Student_ID | Name | Course_ID | Course_ID | Course_Name |
|-----------|--------|----------|----------|-------------|
| 1 | Alice | C101 | C101 | Python |
| 2 | Bob | C102 | C102 | SQL |
| 3 | Charlie| C103 | C103 | Power BI |
| 4 | David | NULL | | |
πΉ David has no course assigned (NULL value in Course_ID).
πΉ To get only students who are enrolled in a course, we use
INNER JOIN
.SELECT Students.Name, Courses.Course_Name
FROM Students
INNER JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
πΉ Output:
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
π David is not included because he has no matching Course_ID.
---
πΉ Understanding LEFT JOIN
πΉ LEFT JOIN returns ALL records from the left table (Students) and matching records from the right table (Courses).
πΉ If there is no match, NULL is returned.
SELECT Students.Name, Courses.Course_Name
FROM Students
LEFT JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
πΉ Output (Now including David too):
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| David | NULL |
π David is included, but Course_Name is NULL because there is no matching Course_ID.
---
π― Hands-On Practice: Solve These SQL Problems
1οΈβ£ Find all students who are enrolled in a course (Use
INNER JOIN
). SELECT Students.Name, Courses.Course_Name
FROM Students
INNER JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
2οΈβ£ Find all students, even those without courses (Use
LEFT JOIN
). SELECT Students.Name, Courses.Course_Name
FROM Students
LEFT JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
3οΈβ£ Find courses that have students enrolled (Use
INNER JOIN
with Course as the left table). SELECT Courses.Course_Name, Students.Name
FROM Courses
INNER JOIN Students
ON Students.Course_ID = Courses.Course_ID;
π Your Tasks for Today
β Revise INNER JOIN & LEFT JOIN.
β Run the practice queries in SQL.
β Try at least 3 SQL JOIN problems on HackerRank or LeetCode.
β Comment "Done β " once you complete today's practice!
Tomorrow, weβll explore RIGHT JOIN, FULL JOIN, and SELF JOIN!
π Like β€οΈ and Share if youβre excited for Day 9! π
β€4π2
Day 9: SQL JOINS Continued β RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN π
Welcome back! Yesterday, we learned about INNER JOIN and LEFT JOIN, which help us combine data from multiple tables. Today, weβll continue exploring more SQL JOINS, including:
βοΈ RIGHT JOIN β Opposite of LEFT JOIN
βοΈ FULL OUTER JOIN β Returns all records from both tables
βοΈ SELF JOIN β Joining a table with itself
By the end of todayβs lesson, youβll have a strong understanding of how to combine data across tables efficiently.
---
π Recap of JOINS
πΉ INNER JOIN β Returns only matching records from both tables.
πΉ LEFT JOIN β Returns all records from the left table, with matching records from the right table.
Now, letβs move on to RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN.
---
πΉ RIGHT JOIN β The Opposite of LEFT JOIN
πΉ RIGHT JOIN (or RIGHT OUTER JOIN) returns:
β All records from the right table
β Matching records from the left table
β If thereβs no match, the left table will show
π― Example: Students and Courses
| Students Table | | Courses Table |
|------------------|-----------------|------------------|
| Student_ID | Name | Course_ID | Course_ID | Course_Name |
|-----------|--------|----------|----------|-------------|
| 1 | Alice | C101 | C101 | Python |
| 2 | Bob | C102 | C102 | SQL |
| 3 | Charlie| C103 | C103 | Power BI |
| 4 | David | NULL | C104 | JavaScript |
πΉ C104 (JavaScript) has no students enrolled.
π RIGHT JOIN Query:
πΉ Output
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| NULL | JavaScript |
π JavaScript is included, but no student is enrolled (NULL in Name column).
π Key Takeaway:
Use RIGHT JOIN when you want all data from the right table and matching data from the left.
---
πΉ FULL OUTER JOIN β All Data from Both Tables
πΉ FULL OUTER JOIN returns:
β All records from both tables
β If thereβs no match,
π FULL OUTER JOIN Query:
πΉ Output
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| David | NULL |
| NULL | JavaScript |
π David (who has no course) and JavaScript (which has no students) are both included.
π Key Takeaway:
Use FULL OUTER JOIN when you need all data from both tables, even if thereβs no match.
βοΈ Note: Not all databases support
---
πΉ SELF JOIN β When a Table Joins Itself
πΉ Sometimes, a table contains hierarchical or related data within itself.
πΉ A SELF JOIN allows a table to join with itself to compare data in different rows.
π― Example: Employee Hierarchy
| Employee_ID | Name | Manager_ID |
|------------|--------|------------|
| 1 | Alice | NULL |
| 2 | Bob | 1 |
| 3 | Charlie| 1 |
| 4 | David | 2 |
πΉ Here, Bob and Charlie report to Alice, and David reports to Bob.
π SELF JOIN Query to Find Employee-Manager Relationship:
πΉ Output
| Employee | Manager |
|----------|---------|
| Alice | NULL |
| Bob | Alice |
| Charlie | Alice |
| David | Bob |
π Alice has no manager (NULL), Bob & Charlie report to Alice, and David reports to Bob.
Welcome back! Yesterday, we learned about INNER JOIN and LEFT JOIN, which help us combine data from multiple tables. Today, weβll continue exploring more SQL JOINS, including:
βοΈ RIGHT JOIN β Opposite of LEFT JOIN
βοΈ FULL OUTER JOIN β Returns all records from both tables
βοΈ SELF JOIN β Joining a table with itself
By the end of todayβs lesson, youβll have a strong understanding of how to combine data across tables efficiently.
---
π Recap of JOINS
πΉ INNER JOIN β Returns only matching records from both tables.
πΉ LEFT JOIN β Returns all records from the left table, with matching records from the right table.
Now, letβs move on to RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN.
---
πΉ RIGHT JOIN β The Opposite of LEFT JOIN
πΉ RIGHT JOIN (or RIGHT OUTER JOIN) returns:
β All records from the right table
β Matching records from the left table
β If thereβs no match, the left table will show
NULL
values π― Example: Students and Courses
| Students Table | | Courses Table |
|------------------|-----------------|------------------|
| Student_ID | Name | Course_ID | Course_ID | Course_Name |
|-----------|--------|----------|----------|-------------|
| 1 | Alice | C101 | C101 | Python |
| 2 | Bob | C102 | C102 | SQL |
| 3 | Charlie| C103 | C103 | Power BI |
| 4 | David | NULL | C104 | JavaScript |
πΉ C104 (JavaScript) has no students enrolled.
π RIGHT JOIN Query:
SELECT Students.Name, Courses.Course_Name
FROM Students
RIGHT JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
πΉ Output
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| NULL | JavaScript |
π JavaScript is included, but no student is enrolled (NULL in Name column).
π Key Takeaway:
Use RIGHT JOIN when you want all data from the right table and matching data from the left.
---
πΉ FULL OUTER JOIN β All Data from Both Tables
πΉ FULL OUTER JOIN returns:
β All records from both tables
β If thereβs no match,
NULL
values will be filled π FULL OUTER JOIN Query:
SELECT Students.Name, Courses.Course_Name
FROM Students
FULL OUTER JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
πΉ Output
| Name | Course_Name |
|-------|------------|
| Alice | Python |
| Bob | SQL |
| Charlie | Power BI |
| David | NULL |
| NULL | JavaScript |
π David (who has no course) and JavaScript (which has no students) are both included.
π Key Takeaway:
Use FULL OUTER JOIN when you need all data from both tables, even if thereβs no match.
βοΈ Note: Not all databases support
FULL OUTER JOIN
. If yours doesnβt, you can simulate it using `UNION`:SELECT Students.Name, Courses.Course_Name
FROM Students
LEFT JOIN Courses ON Students.Course_ID = Courses.Course_ID
UNION
SELECT Students.Name, Courses.Course_Name
FROM Students
RIGHT JOIN Courses ON Students.Course_ID = Courses.Course_ID;
---
πΉ SELF JOIN β When a Table Joins Itself
πΉ Sometimes, a table contains hierarchical or related data within itself.
πΉ A SELF JOIN allows a table to join with itself to compare data in different rows.
π― Example: Employee Hierarchy
| Employee_ID | Name | Manager_ID |
|------------|--------|------------|
| 1 | Alice | NULL |
| 2 | Bob | 1 |
| 3 | Charlie| 1 |
| 4 | David | 2 |
πΉ Here, Bob and Charlie report to Alice, and David reports to Bob.
π SELF JOIN Query to Find Employee-Manager Relationship:
SELECT E1.Name AS Employee, E2.Name AS Manager
FROM Employees E1
LEFT JOIN Employees E2
ON E1.Manager_ID = E2.Employee_ID;
πΉ Output
| Employee | Manager |
|----------|---------|
| Alice | NULL |
| Bob | Alice |
| Charlie | Alice |
| David | Bob |
π Alice has no manager (NULL), Bob & Charlie report to Alice, and David reports to Bob.
π2
π Key Takeaway:
Use SELF JOIN when working with hierarchical data like employees and managers, product categories, etc.
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Get all students and their courses using RIGHT JOIN.
2οΈβ£ List all students and all courses, even if there is no match (FULL OUTER JOIN).
3οΈβ£ Find employee-manager relationships using SELF JOIN.
---
π Your Tasks for Today
β Revise RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN.
β Run the practice queries in SQL.
β Try at least 3 SQL JOIN problems on HackerRank or LeetCode.
β Comment "Done β " once you complete today's practice!
Tomorrow, weβll explore NULL values and how to handle them in SQL!
π Like β€οΈ and Share if youβre excited for Day 10! π
Use SELF JOIN when working with hierarchical data like employees and managers, product categories, etc.
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Get all students and their courses using RIGHT JOIN.
SELECT Students.Name, Courses.Course_Name
FROM Students
RIGHT JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
2οΈβ£ List all students and all courses, even if there is no match (FULL OUTER JOIN).
SELECT Students.Name, Courses.Course_Name
FROM Students
FULL OUTER JOIN Courses
ON Students.Course_ID = Courses.Course_ID;
3οΈβ£ Find employee-manager relationships using SELF JOIN.
SELECT E1.Name AS Employee, E2.Name AS Manager
FROM Employees E1
LEFT JOIN Employees E2
ON E1.Manager_ID = E2.Employee_ID;
---
π Your Tasks for Today
β Revise RIGHT JOIN, FULL OUTER JOIN, and SELF JOIN.
β Run the practice queries in SQL.
β Try at least 3 SQL JOIN problems on HackerRank or LeetCode.
β Comment "Done β " once you complete today's practice!
Tomorrow, weβll explore NULL values and how to handle them in SQL!
π Like β€οΈ and Share if youβre excited for Day 10! π
β€2
Day 10: Working with NULL Values & Using CASE Statements in SQL
Welcome back! Today, weβre going to cover two important SQL topics:
βοΈ NULL values β What they are and how to handle them.
βοΈ CASE statements β A powerful way to apply conditional logic in SQL.
By the end of todayβs lesson, youβll understand how to deal with missing data (
---
π What is NULL in SQL?
πΉ In SQL, NULL means "missing" or "unknown" data.
πΉ It is not the same as
πΉ When a column has
π― Example: Employee Salaries
| Employee_ID | Name | Salary |
|------------|--------|--------|
| 1 | Alice | 50000 |
| 2 | Bob | NULL |
| 3 | Charlie| 60000 |
| 4 | David | NULL |
Bob and David have NULL salaries, meaning we donβt know their salary yet.
---
πΉ How to Handle NULL Values in SQL
1οΈβ£ Checking for NULL using `IS NULL` and `IS NOT NULL`
π Find employees whose salary is missing:
πΉ Output:
| Name |
|-------|
| Bob |
| David |
π Find employees whose salary is known:
πΉ Output:
| Name | Salary |
|--------|--------|
| Alice | 50000 |
| Charlie| 60000 |
π Important: You cannot check
---
2οΈβ£ Replacing NULL Values Using `COALESCE()`
πΉ COALESCE() replaces `NULL` with a default value.
π Example: Replace NULL salaries with "Not Assigned"
πΉ Output:
| Name | Salary |
|---------|-------------|
| Alice | 50000 |
| Bob | Not Assigned |
| Charlie | 60000 |
| David | Not Assigned |
π‘ `COALESCE()` takes multiple values and returns the first non-NULL value.
---
3οΈβ£ Handling NULL in Aggregations
πΉ Aggregate functions (SUM, AVG, COUNT, etc.) automatically ignore NULLs.
π Find total salary of all employees:
πΉ Output:
| Total_Salary |
|-------------|
| 110000 |
π NULL salaries are ignored in SUM.
π Find average salary (excluding NULL values):
πΉ Output:
| Avg_Salary |
|-----------|
| 55000 |
πΉ If you want to include NULL as 0 in calculations, use
πΉ Output:
| Avg_Salary |
|-----------|
| 36666.67 |
Now, let's move on to CASE statements.
---
πΉ Using CASE Statements in SQL
πΉ
πΉ It allows you to return different values based on conditions.
π― Example: Categorizing Employees by Salary
πΉ Output:
| Name | Salary | Salary_Category |
|---------|--------|----------------|
| Alice | 50000 | Medium Salary |
| Bob | NULL | Low Salary |
| Charlie | 60000 | High Salary |
| David | NULL | Low Salary |
π NULL values are treated as `ELSE` conditions unless handled separately.
π Handling NULL separately in CASE:
πΉ Now, NULL values are labeled as "Salary Not Available".
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Find all employees whose salary is NULL.
2οΈβ£ Replace NULL salaries with 0.
Welcome back! Today, weβre going to cover two important SQL topics:
βοΈ NULL values β What they are and how to handle them.
βοΈ CASE statements β A powerful way to apply conditional logic in SQL.
By the end of todayβs lesson, youβll understand how to deal with missing data (
NULL
) and how to write conditional logic directly in SQL queries. ---
π What is NULL in SQL?
πΉ In SQL, NULL means "missing" or "unknown" data.
πΉ It is not the same as
0
or an empty string (""
). πΉ When a column has
NULL
, it means no value has been assigned yet. π― Example: Employee Salaries
| Employee_ID | Name | Salary |
|------------|--------|--------|
| 1 | Alice | 50000 |
| 2 | Bob | NULL |
| 3 | Charlie| 60000 |
| 4 | David | NULL |
Bob and David have NULL salaries, meaning we donβt know their salary yet.
---
πΉ How to Handle NULL Values in SQL
1οΈβ£ Checking for NULL using `IS NULL` and `IS NOT NULL`
π Find employees whose salary is missing:
SELECT Name
FROM Employees
WHERE Salary IS NULL;
πΉ Output:
| Name |
|-------|
| Bob |
| David |
π Find employees whose salary is known:
SELECT Name, Salary
FROM Employees
WHERE Salary IS NOT NULL;
πΉ Output:
| Name | Salary |
|--------|--------|
| Alice | 50000 |
| Charlie| 60000 |
π Important: You cannot check
NULL
with = NULL
or != NULL
. Always use IS NULL
or IS NOT NULL
.---
2οΈβ£ Replacing NULL Values Using `COALESCE()`
πΉ COALESCE() replaces `NULL` with a default value.
π Example: Replace NULL salaries with "Not Assigned"
SELECT Name, COALESCE(Salary, 'Not Assigned') AS Salary
FROM Employees;
πΉ Output:
| Name | Salary |
|---------|-------------|
| Alice | 50000 |
| Bob | Not Assigned |
| Charlie | 60000 |
| David | Not Assigned |
π‘ `COALESCE()` takes multiple values and returns the first non-NULL value.
---
3οΈβ£ Handling NULL in Aggregations
πΉ Aggregate functions (SUM, AVG, COUNT, etc.) automatically ignore NULLs.
π Find total salary of all employees:
SELECT SUM(Salary) AS Total_Salary
FROM Employees;
πΉ Output:
| Total_Salary |
|-------------|
| 110000 |
π NULL salaries are ignored in SUM.
π Find average salary (excluding NULL values):
SELECT AVG(Salary) AS Avg_Salary
FROM Employees;
πΉ Output:
| Avg_Salary |
|-----------|
| 55000 |
πΉ If you want to include NULL as 0 in calculations, use
COALESCE(Salary, 0)
: SELECT AVG(COALESCE(Salary, 0)) AS Avg_Salary
FROM Employees;
πΉ Output:
| Avg_Salary |
|-----------|
| 36666.67 |
Now, let's move on to CASE statements.
---
πΉ Using CASE Statements in SQL
πΉ
CASE
is like an IF-ELSE statement in SQL. πΉ It allows you to return different values based on conditions.
π― Example: Categorizing Employees by Salary
SELECT Name, Salary,
CASE
WHEN Salary >= 60000 THEN 'High Salary'
WHEN Salary >= 40000 THEN 'Medium Salary'
ELSE 'Low Salary'
END AS Salary_Category
FROM Employees;
πΉ Output:
| Name | Salary | Salary_Category |
|---------|--------|----------------|
| Alice | 50000 | Medium Salary |
| Bob | NULL | Low Salary |
| Charlie | 60000 | High Salary |
| David | NULL | Low Salary |
π NULL values are treated as `ELSE` conditions unless handled separately.
π Handling NULL separately in CASE:
SELECT Name,
CASE
WHEN Salary IS NULL THEN 'Salary Not Available'
WHEN Salary >= 60000 THEN 'High Salary'
WHEN Salary >= 40000 THEN 'Medium Salary'
ELSE 'Low Salary'
END AS Salary_Category
FROM Employees;
πΉ Now, NULL values are labeled as "Salary Not Available".
---
π― Hands-On Practice: Try These Queries
1οΈβ£ Find all employees whose salary is NULL.
SELECT Name FROM Employees WHERE Salary IS NULL;
2οΈβ£ Replace NULL salaries with 0.
SELECT Name, COALESCE(Salary, 0) AS Salary FROM Employees;
π4