๐ SQL Roadmap 2026 โ Part 2
SQL SELECT Statement & Retrieving Data
Now that you understand databases, tables, rows, columns, primary keys, and foreign keys, it's time to learn the most fundamental SQL command: SELECT.
Almost every SQL analysis starts with retrieving data.
1๏ธโฃ What is SELECT?
SELECT is used to retrieve data from one or more columns in a table.
Basic syntax:
Example:
2๏ธโฃ Select Multiple Columns
You can retrieve multiple columns by separating them with commas.
Result:
customer_id | customer_name | city
1 | Rahul | Mumbai
2 | Priya | Delhi
3 | Amit | Pune
3๏ธโฃ Select All Columns Using *
If you want every column:
โ ๏ธ Interview Tip: Although
4๏ธโฃ Column Aliases
Use AS to give a column a different name in the result.
The original table is not changed.
5๏ธโฃ Aliases Without AS
However, using AS is generally clearer for beginners.
6๏ธโฃ Calculations Inside SELECT
7๏ธโฃ Arithmetic Operators
8๏ธโฃ Using Expressions
9๏ธโฃ DISTINCT
Removes duplicate values.
๐ DISTINCT Across Multiple Columns
1๏ธโฃ1๏ธโฃ Using SELECT With Text
1๏ธโฃ2๏ธโฃ Combining Columns
1๏ธโฃ3๏ธโฃ SELECT With a Condition
1๏ธโฃ5๏ธโฃ SQL Query Structure
At this stage, learn this basic pattern:
1๏ธโฃ6๏ธโฃ A Real-World Example
Manager asks: "Show me product name, selling price, cost price, and profit"
SQL SELECT Statement & Retrieving Data
Now that you understand databases, tables, rows, columns, primary keys, and foreign keys, it's time to learn the most fundamental SQL command: SELECT.
Almost every SQL analysis starts with retrieving data.
1๏ธโฃ What is SELECT?
SELECT is used to retrieve data from one or more columns in a table.
Basic syntax:
SELECT column_name
FROM table_name;
Example:
SELECT customer_name
FROM customers;
2๏ธโฃ Select Multiple Columns
You can retrieve multiple columns by separating them with commas.
SELECT
customer_id,
customer_name,
city
FROM customers;
Result:
customer_id | customer_name | city
1 | Rahul | Mumbai
2 | Priya | Delhi
3 | Amit | Pune
3๏ธโฃ Select All Columns Using *
If you want every column:
SELECT *
FROM customers;
* means all columns.โ ๏ธ Interview Tip: Although
SELECT * is convenient while exploring data, avoid relying on it in production queries. Prefer selecting only needed columns.4๏ธโฃ Column Aliases
Use AS to give a column a different name in the result.
SELECT
customer_name AS name,
city AS location
FROM customers;
The original table is not changed.
5๏ธโฃ Aliases Without AS
SELECT
customer_name name,
city location
FROM customers;
However, using AS is generally clearer for beginners.
6๏ธโฃ Calculations Inside SELECT
SELECT
product_name,
price,
price * 0.90 AS discounted_price
FROM products;
7๏ธโฃ Arithmetic Operators
+ Addition, - Subtraction, * Multiplication, / DivisionSELECT
product_name,
selling_price,
cost_price,
selling_price - cost_price AS profit
FROM products;
8๏ธโฃ Using Expressions
SELECT
product_name,
quantity,
unit_price,
quantity * unit_price AS total_value
FROM order_items;
9๏ธโฃ DISTINCT
Removes duplicate values.
SELECT DISTINCT city
FROM customers;
๐ DISTINCT Across Multiple Columns
SELECT DISTINCT
city,
customer_segment
FROM customers;
1๏ธโฃ1๏ธโฃ Using SELECT With Text
SELECT
customer_name,
'Active Customer' AS status
FROM customers;
1๏ธโฃ2๏ธโฃ Combining Columns
SELECT
first_name,
last_name,
CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;
1๏ธโฃ3๏ธโฃ SELECT With a Condition
SELECT
customer_name,
city
FROM customers
WHERE city = 'Mumbai';
1๏ธโฃ5๏ธโฃ SQL Query Structure
At this stage, learn this basic pattern:
SELECT column1, column2
FROM table_name;
SELECT column1, column2
FROM table_name
WHERE condition;
1๏ธโฃ6๏ธโฃ A Real-World Example
Manager asks: "Show me product name, selling price, cost price, and profit"
SELECT
product_name,
selling_price,
cost_price,
selling_price - cost_price AS profit
FROM products;
โค5
๐ง Common Beginner Mistakes
โ Mistake 1: Forgetting FROM
Wrong: SELECT customer_name;
Correct: SELECT customer_name FROM customers;
โ Mistake 2: Using commas incorrectly
Wrong: SELECT customer_id customer_name city
Correct: Use commas
โ Mistake 3: Using quotes around column names unnecessarily
โ Mistake 4: Confusing
๐ฏ Practice Questions
Q1. Display all columns from employees
Q2. Display employee_name, salary, department_id
Q3. Display unique cities from customers
Q4. Display product_name, price and 15% discounted price
Q5. Display product_name, selling_price, cost_price and profit
Q6. Display customer names with alias Customer
Q7. Display employee name and salary increased by 10%
โ Answers
๐ผ Interview Questions
1. What does SELECT do? โ Retrieves data from columns.
2. What does SELECT * mean? โ Retrieves all columns.
3. What is DISTINCT? โ Removes duplicate combinations.
4. What is an alias? โ Temporary name for clarity.
5. Can SQL perform calculations? โ Yes, arithmetic expressions directly in queries.
Double Tap โค๏ธ For Part-3
โ Mistake 1: Forgetting FROM
Wrong: SELECT customer_name;
Correct: SELECT customer_name FROM customers;
โ Mistake 2: Using commas incorrectly
Wrong: SELECT customer_id customer_name city
Correct: Use commas
โ Mistake 3: Using quotes around column names unnecessarily
SELECT 'customer_name' treats it as text, not column. โ Mistake 4: Confusing
*SELECT * means return all columns, not all rows. ๐ฏ Practice Questions
Q1. Display all columns from employees
Q2. Display employee_name, salary, department_id
Q3. Display unique cities from customers
Q4. Display product_name, price and 15% discounted price
Q5. Display product_name, selling_price, cost_price and profit
Q6. Display customer names with alias Customer
Q7. Display employee name and salary increased by 10%
โ Answers
-- A1
SELECT * FROM employees;
-- A2
SELECT employee_name, salary, department_id FROM employees;
-- A3
SELECT DISTINCT city FROM customers;
-- A4
SELECT product_name, price, price * 0.85 AS discounted_price FROM products;
-- A5
SELECT product_name, selling_price, cost_price, selling_price - cost_price AS profit FROM products;
-- A6
SELECT customer_name AS Customer FROM customers;
-- A7
SELECT employee_name, salary, salary * 1.10 AS increased_salary FROM employees;
๐ผ Interview Questions
1. What does SELECT do? โ Retrieves data from columns.
2. What does SELECT * mean? โ Retrieves all columns.
3. What is DISTINCT? โ Removes duplicate combinations.
4. What is an alias? โ Temporary name for clarity.
5. Can SQL perform calculations? โ Yes, arithmetic expressions directly in queries.
Double Tap โค๏ธ For Part-3
โค11
๐ SQL Roadmap 2026 โ Part 4
Sorting, Limiting & Selecting the Right Records
In the previous part, you learned how to filter data using WHERE.
Now we'll learn how to control which records appear first, last, or how many records are returned.
These concepts are simple, but they are extremely important for SQL interviews and real-world analytics.
1๏ธโฃ ORDER BY
ORDER BY is used to sort query results.
Syntax
By default, SQL sorts in ascending order (ASC).
Example:
This displays employees from the lowest salary to the highest.
2๏ธโฃ ASC โ Ascending Order
You can explicitly specify ASC.
For numbers:
100, 250, 500, 1000
For text:
Amit, Neha, Priya, Rahul
3๏ธโฃ DESC โ Descending Order
Use DESC when you want the highest values first.
Result:
Amit: 1200000, Priya: 950000, Rahul: 850000, Neha: 650000
This is one of the most commonly used SQL patterns.
4๏ธโฃ Real-World Example: Top Salaries
Business requirement:
But this might return thousands of employees.
That's where LIMIT becomes useful.
5๏ธโฃ LIMIT
LIMIT restricts the number of rows returned.
This returns only the top 5 employees by salary.
Think of it as:
ORDER BY DESC โ Highest first โ LIMIT 5 โ Keep first 5
6๏ธโฃ Top 10 Products by Price
Very common in analytics.
7๏ธโฃ LIMIT Without ORDER BY
You technically can write:
But this means:
It does not mean:
Without ORDER BY, the returned order should generally not be relied upon.
If you want the top 10 customers by revenue:
8๏ธโฃ OFFSET
OFFSET allows you to skip a number of rows.
Example:
This skips the first 5 rows and returns the next 5.
Conceptually:
Rows 1โ5 โ Skip, Rows 6โ10 โ Return
9๏ธโฃ Pagination
LIMIT and OFFSET are often used for pagination.
For example:
Page 1
Page 2
Page 3
The general pattern is:
Page 1 โ OFFSET 0, Page 2 โ OFFSET 10, Page 3 โ OFFSET 20
๐ Sorting by Multiple Columns
You can sort using more than one column.
Example:
Sorting, Limiting & Selecting the Right Records
In the previous part, you learned how to filter data using WHERE.
Now we'll learn how to control which records appear first, last, or how many records are returned.
These concepts are simple, but they are extremely important for SQL interviews and real-world analytics.
1๏ธโฃ ORDER BY
ORDER BY is used to sort query results.
Syntax
SELECT column1, column2
FROM table_name
ORDER BY column_name;
By default, SQL sorts in ascending order (ASC).
Example:
SELECT
employee_name,
salary
FROM employees
ORDER BY salary;
This displays employees from the lowest salary to the highest.
2๏ธโฃ ASC โ Ascending Order
You can explicitly specify ASC.
SELECT
employee_name,
salary
FROM employees
ORDER BY salary ASC;
For numbers:
100, 250, 500, 1000
For text:
Amit, Neha, Priya, Rahul
3๏ธโฃ DESC โ Descending Order
Use DESC when you want the highest values first.
SELECT
employee_name,
salary
FROM employees
ORDER BY salary DESC;
Result:
Amit: 1200000, Priya: 950000, Rahul: 850000, Neha: 650000
This is one of the most commonly used SQL patterns.
4๏ธโฃ Real-World Example: Top Salaries
Business requirement:
Find the highest-paid employees.
SELECT
employee_name,
salary
FROM employees
ORDER BY salary DESC;
But this might return thousands of employees.
That's where LIMIT becomes useful.
5๏ธโฃ LIMIT
LIMIT restricts the number of rows returned.
SELECT
employee_name,
salary
FROM employees
ORDER BY salary DESC
LIMIT 5;
This returns only the top 5 employees by salary.
Think of it as:
ORDER BY DESC โ Highest first โ LIMIT 5 โ Keep first 5
6๏ธโฃ Top 10 Products by Price
SELECT
product_name,
price
FROM products
ORDER BY price DESC
LIMIT 10;
Very common in analytics.
7๏ธโฃ LIMIT Without ORDER BY
You technically can write:
SELECT *
FROM customers
LIMIT 10;
But this means:
Give me 10 rows.
It does not mean:
Give me the first 10 rows according to some meaningful business order.
Without ORDER BY, the returned order should generally not be relied upon.
If you want the top 10 customers by revenue:
SELECT
customer_id,
revenue
FROM customer_revenue
ORDER BY revenue DESC
LIMIT 10;
8๏ธโฃ OFFSET
OFFSET allows you to skip a number of rows.
Example:
SELECT
employee_name,
salary
FROM employees
ORDER BY salary DESC
LIMIT 5 OFFSET 5;
This skips the first 5 rows and returns the next 5.
Conceptually:
Rows 1โ5 โ Skip, Rows 6โ10 โ Return
9๏ธโฃ Pagination
LIMIT and OFFSET are often used for pagination.
For example:
Page 1
SELECT *
FROM customers
ORDER BY customer_id
LIMIT 10 OFFSET 0;
Page 2
SELECT *
FROM customers
ORDER BY customer_id
LIMIT 10 OFFSET 10;
Page 3
SELECT *
FROM customers
ORDER BY customer_id
LIMIT 10 OFFSET 20;
The general pattern is:
Page 1 โ OFFSET 0, Page 2 โ OFFSET 10, Page 3 โ OFFSET 20
๐ Sorting by Multiple Columns
You can sort using more than one column.
Example:
SELECT
employee_name,
department,
salary
FROM employees
ORDER BY department ASC, salary DESC;
โค2
SQL first sorts by:
department
Then within each department:
salary DESC
Example:
Finance: 950000, Finance: 750000, IT: 1200000, IT: 850000, IT: 700000
1๏ธโฃ1๏ธโฃ Why Multiple Sorting Columns Matter
Suppose several products have the same price.
Laptop: 50000, Phone: 50000, Tablet: 50000
You can add a second sorting condition:
Now SQL uses the product name to break ties.
1๏ธโฃ2๏ธโฃ Sorting by Calculated Values
You can sort using an expression.
Example:
This displays the products with the highest calculated profit first.
1๏ธโฃ3๏ธโฃ Sorting by an Alias
You can usually sort using a column alias defined in the SELECT list.
This is convenient and makes the query easier to read.
1๏ธโฃ4๏ธโฃ Sorting by Column Position
Some SQL dialects allow:
Here:
1 โ product_name, 2 โ price
So SQL sorts by the second selected column.
โ ๏ธ Best Practice
Although positional ordering may be supported, prefer:
ORDER BY price DESC;
because it is easier to understand and less fragile if the SELECT list changes.
1๏ธโฃ5๏ธโฃ NULL Values and ORDER BY
NULL values require special attention.
For example:
Rahul: 5000, Priya: NULL, Amit: 8000
The position of NULL values when sorting can vary by database system and sort direction.
Some systems allow explicit control:
ORDER BY bonus DESC NULLS LAST;
or:
ORDER BY bonus ASC NULLS FIRST;
Interview Tip
Don't assume NULL sorting behavior is identical across MySQL, PostgreSQL, SQL Server, and Oracle.
1๏ธโฃ6๏ธโฃ ORDER BY With WHERE
You can combine filtering and sorting.
Example:
Execution conceptually works as:
FROM โ WHERE โ SELECT โ ORDER BY
The detailed logical processing order has a few nuances, but this is a useful beginner mental model.
1๏ธโฃ7๏ธโฃ ORDER BY With LIMIT
This combination is extremely important.
Requirement:
This pattern appears constantly in SQL interviews.
1๏ธโฃ8๏ธโฃ Top N Per Category
Here's an important distinction.
Suppose you need:
You can use:
ORDER BY revenue DESC LIMIT 3;
But if the requirement is:
LIMIT 3 alone isn't enough.
You'll eventually need window functions such as ROW_NUMBER() or DENSE_RANK().
Example:
Don't worry if this looks advanced.
You'll learn window functions later.
1๏ธโฃ9๏ธโฃ DISTINCT & ORDER BY
You can combine DISTINCT and ORDER BY.
Example:
department
Then within each department:
salary DESC
Example:
Finance: 950000, Finance: 750000, IT: 1200000, IT: 850000, IT: 700000
1๏ธโฃ1๏ธโฃ Why Multiple Sorting Columns Matter
Suppose several products have the same price.
Laptop: 50000, Phone: 50000, Tablet: 50000
You can add a second sorting condition:
SELECT
product_name,
price
FROM products
ORDER BY
price DESC,
product_name ASC;
Now SQL uses the product name to break ties.
1๏ธโฃ2๏ธโฃ Sorting by Calculated Values
You can sort using an expression.
Example:
SELECT
product_name,
selling_price,
cost_price,
selling_price - cost_price AS profit
FROM products
ORDER BY profit DESC;
This displays the products with the highest calculated profit first.
1๏ธโฃ3๏ธโฃ Sorting by an Alias
You can usually sort using a column alias defined in the SELECT list.
SELECT
product_name,
selling_price - cost_price AS profit
FROM products
ORDER BY profit DESC;
This is convenient and makes the query easier to read.
1๏ธโฃ4๏ธโฃ Sorting by Column Position
Some SQL dialects allow:
SELECT
product_name,
price
FROM products
ORDER BY 2 DESC;
Here:
1 โ product_name, 2 โ price
So SQL sorts by the second selected column.
โ ๏ธ Best Practice
Although positional ordering may be supported, prefer:
ORDER BY price DESC;
because it is easier to understand and less fragile if the SELECT list changes.
1๏ธโฃ5๏ธโฃ NULL Values and ORDER BY
NULL values require special attention.
For example:
Rahul: 5000, Priya: NULL, Amit: 8000
The position of NULL values when sorting can vary by database system and sort direction.
Some systems allow explicit control:
ORDER BY bonus DESC NULLS LAST;
or:
ORDER BY bonus ASC NULLS FIRST;
Interview Tip
Don't assume NULL sorting behavior is identical across MySQL, PostgreSQL, SQL Server, and Oracle.
1๏ธโฃ6๏ธโฃ ORDER BY With WHERE
You can combine filtering and sorting.
Example:
Find Mumbai customers and display the highest spenders first.
SELECT
customer_name,
city,
total_spend
FROM customers
WHERE city = 'Mumbai'
ORDER BY total_spend DESC;
Execution conceptually works as:
FROM โ WHERE โ SELECT โ ORDER BY
The detailed logical processing order has a few nuances, but this is a useful beginner mental model.
1๏ธโฃ7๏ธโฃ ORDER BY With LIMIT
This combination is extremely important.
Requirement:
Find the top 3 customers by spending.
SELECT
customer_name,
total_spend
FROM customers
ORDER BY total_spend DESC
LIMIT 3;
This pattern appears constantly in SQL interviews.
1๏ธโฃ8๏ธโฃ Top N Per Category
Here's an important distinction.
Suppose you need:
Top 3 products overall.
You can use:
ORDER BY revenue DESC LIMIT 3;
But if the requirement is:
Top 3 products in every category
LIMIT 3 alone isn't enough.
You'll eventually need window functions such as ROW_NUMBER() or DENSE_RANK().
Example:
WITH ranked_products AS (
SELECT
product_name,
category,
revenue,
ROW_NUMBER() OVER (
PARTITION BY category
ORDER BY revenue DESC
) AS rn
FROM product_sales
)
SELECT
product_name,
category,
revenue
FROM ranked_products
WHERE rn <= 3;
Don't worry if this looks advanced.
You'll learn window functions later.
1๏ธโฃ9๏ธโฃ DISTINCT & ORDER BY
You can combine DISTINCT and ORDER BY.
Example:
SELECT DISTINCT city
FROM customers
ORDER BY city ASC;
Result:
Bangalore, Delhi, Hyderabad, Mumbai, Pune
2๏ธโฃ0๏ธโฃ ORDER BY Multiple Columns With Different Directions
You can specify different directions.
Meaning:
Department โ A to Z, Salary โ Highest to Lowest within department
2๏ธโฃ1๏ธโฃ Real-World Business Example
Requirement:
Notice the combination:
WHERE โ Filter active products, ORDER BY โ Highest price first, LIMIT โ Keep only 5
2๏ธโฃ2๏ธโฃ Another Example
Requirement:
This is a classic Data Analyst query.
๐ง Common Beginner Mistakes
โ Mistake 1: Forgetting DESC
If you want the highest values first:
ORDER BY salary DESC;
Not:
ORDER BY salary;
because the default is typically ascending.
โ Mistake 2: Using LIMIT without ORDER BY
This:
doesn't reliably identify the "top 5" by any business metric.
Instead:
โ Mistake 3: Confusing LIMIT with filtering
LIMIT doesn't filter rows based on a condition.
LIMIT 10 means:
Whereas:
WHERE salary > 800000 means:
โ Mistake 4: Using LIMIT for Top N per Group
ORDER BY revenue DESC LIMIT 3; returns 3 rows overall.
It does not return 3 rows from every category.
๐ผ SQL Interview Questions
Q1. What is ORDER BY?
Answer: ORDER BY sorts the result set according to one or more columns or expressions.
Q2. What is the default sorting direction?
Answer: Ascending (ASC) is the default in standard SQL usage.
Q3. How do you find the highest-paid employee?
Q4. How do you find the top 5 products by revenue?
Q5. What does OFFSET do?
Answer: OFFSET skips a specified number of rows before returning the remaining rows subject to LIMIT or the database's equivalent pagination mechanism.
Q6. Can you sort by multiple columns?
Answer: Yes. ORDER BY department, salary DESC;
Q7. Can you use an alias in ORDER BY?
Answer: In most common SQL systems, yes.
Bangalore, Delhi, Hyderabad, Mumbai, Pune
2๏ธโฃ0๏ธโฃ ORDER BY Multiple Columns With Different Directions
You can specify different directions.
SELECT
department,
employee_name,
salary
FROM employees
ORDER BY
department ASC,
salary DESC;
Meaning:
Department โ A to Z, Salary โ Highest to Lowest within department
2๏ธโฃ1๏ธโฃ Real-World Business Example
Requirement:
Show the 5 most expensive products that are currently active.
SELECT
product_name,
category,
price
FROM products
WHERE product_status = 'Active'
ORDER BY price DESC
LIMIT 5;
Notice the combination:
WHERE โ Filter active products, ORDER BY โ Highest price first, LIMIT โ Keep only 5
2๏ธโฃ2๏ธโฃ Another Example
Requirement:
Find the 10 customers with the highest total spending.
SELECT
customer_id,
customer_name,
total_spend
FROM customers
ORDER BY total_spend DESC
LIMIT 10;
This is a classic Data Analyst query.
๐ง Common Beginner Mistakes
โ Mistake 1: Forgetting DESC
If you want the highest values first:
ORDER BY salary DESC;
Not:
ORDER BY salary;
because the default is typically ascending.
โ Mistake 2: Using LIMIT without ORDER BY
This:
SELECT *
FROM products
LIMIT 5;
doesn't reliably identify the "top 5" by any business metric.
Instead:
SELECT *
FROM products
ORDER BY revenue DESC
LIMIT 5;
โ Mistake 3: Confusing LIMIT with filtering
LIMIT doesn't filter rows based on a condition.
LIMIT 10 means:
Return at most 10 rows.
Whereas:
WHERE salary > 800000 means:
Return rows satisfying a condition.
โ Mistake 4: Using LIMIT for Top N per Group
ORDER BY revenue DESC LIMIT 3; returns 3 rows overall.
It does not return 3 rows from every category.
๐ผ SQL Interview Questions
Q1. What is ORDER BY?
Answer: ORDER BY sorts the result set according to one or more columns or expressions.
Q2. What is the default sorting direction?
Answer: Ascending (ASC) is the default in standard SQL usage.
Q3. How do you find the highest-paid employee?
SELECT employee_name, salary FROM employees ORDER BY salary DESC LIMIT 1;
Q4. How do you find the top 5 products by revenue?
SELECT product_name, revenue FROM products ORDER BY revenue DESC LIMIT 5;
Q5. What does OFFSET do?
Answer: OFFSET skips a specified number of rows before returning the remaining rows subject to LIMIT or the database's equivalent pagination mechanism.
Q6. Can you sort by multiple columns?
Answer: Yes. ORDER BY department, salary DESC;
Q7. Can you use an alias in ORDER BY?
Answer: In most common SQL systems, yes.
SELECT salary * 12 AS annual_salary FROM employees ORDER BY annual_salary DESC;
โค2
๐ฏ Practice Questions
Try these yourself first.
Q1. Display all employees sorted by salary from highest to lowest.
Q2. Find the top 5 highest-priced products.
Q3. Display customers alphabetically by name.
Q4. Find the 10 customers with the highest spending.
Q5. Display employees by department alphabetically and salary from highest to lowest within each department.
Q6. Find the 3 cheapest products.
Q7. Display unique customer cities alphabetically.
Q8. Return the second page of 10 customers ordered by customer_id.
Q9. Find the 5 most profitable products.
Q10. Explain why ORDER BY revenue DESC LIMIT 3 cannot directly find the top 3 products in each category.
โ Answers
Answer 1
Answer 2
Answer 3
Answer 4
Answer 5
Answer 6
Answer 7
Answer 8
Answer 9
Answer 10
Because LIMIT 3 applies to the entire result, not separately to each category. To get the top 3 within every category, you need a window function such as ROW_NUMBER() or DENSE_RANK().
๐ฅ Mini Challenge
You have products:
1 Laptop Electronics 90000
2 Phone Electronics 70000
3 Monitor Electronics 50000
4 Chair Furniture 80000
5 Desk Furniture 60000
Business Requirement:
Find the 3 products generating the highest revenue overall.
Steps:
1. Retrieve products, 2. Sort revenue highest โ lowest, 3. Keep 3 rows
The solution is:
Double Tap โค๏ธ For Part-5
Try these yourself first.
Q1. Display all employees sorted by salary from highest to lowest.
Q2. Find the top 5 highest-priced products.
Q3. Display customers alphabetically by name.
Q4. Find the 10 customers with the highest spending.
Q5. Display employees by department alphabetically and salary from highest to lowest within each department.
Q6. Find the 3 cheapest products.
Q7. Display unique customer cities alphabetically.
Q8. Return the second page of 10 customers ordered by customer_id.
Q9. Find the 5 most profitable products.
Q10. Explain why ORDER BY revenue DESC LIMIT 3 cannot directly find the top 3 products in each category.
โ Answers
Answer 1
SELECT employee_name, salary FROM employees ORDER BY salary DESC;
Answer 2
SELECT product_name, price FROM products ORDER BY price DESC LIMIT 5;
Answer 3
SELECT customer_name FROM customers ORDER BY customer_name ASC;
Answer 4
SELECT customer_name, total_spend FROM customers ORDER BY total_spend DESC LIMIT 10;
Answer 5
SELECT employee_name, department, salary FROM employees ORDER BY department ASC, salary DESC;
Answer 6
SELECT product_name, price FROM products ORDER BY price ASC LIMIT 3;
Answer 7
SELECT DISTINCT city FROM customers ORDER BY city ASC;
Answer 8
SELECT * FROM customers ORDER BY customer_id LIMIT 10 OFFSET 10;
Answer 9
SELECT product_name, profit FROM products ORDER BY profit DESC LIMIT 5;
Answer 10
Because LIMIT 3 applies to the entire result, not separately to each category. To get the top 3 within every category, you need a window function such as ROW_NUMBER() or DENSE_RANK().
๐ฅ Mini Challenge
You have products:
1 Laptop Electronics 90000
2 Phone Electronics 70000
3 Monitor Electronics 50000
4 Chair Furniture 80000
5 Desk Furniture 60000
Business Requirement:
Find the 3 products generating the highest revenue overall.
Steps:
1. Retrieve products, 2. Sort revenue highest โ lowest, 3. Keep 3 rows
The solution is:
SELECT product_name, category, revenue FROM products ORDER BY revenue DESC LIMIT 3;
Double Tap โค๏ธ For Part-5
โค5
๐ง๐ผ๐ฝ ๐๐ป-๐๐ฒ๐บ๐ฎ๐ป๐ฑ ๐ฆ๐ธ๐ถ๐น๐น๐ ๐๐ผ ๐๐๐๐๐ฟ๐ฒ-๐ฃ๐ฟ๐ผ๐ผ๐ณ ๐ฌ๐ผ๐๐ฟ ๐๐ฎ๐ฟ๐ฒ๐ฒ๐ฟ ๐
๐ฅ Skills Worth Learning:
โ๏ธ Blockchain
โ๏ธ Cloud Computing
โพ๏ธ DevOps Engineering
๐ค Artificial Intelligence & Machine Learning
๐ Data Science & Analytics
๐ Cybersecurity
๐ฏ Leadership & Communication
๐๐ป๐ฟ๐ผ๐น๐น ๐๐ผ๐ฟ ๐๐ฅ๐๐๐:-
https://pdlinks.in/i89
Donโt just collect certificates โ build projects, gain practical experience and showcase your skills on your resume & LinkedIn.
๐ฅ Skills Worth Learning:
โ๏ธ Blockchain
โ๏ธ Cloud Computing
โพ๏ธ DevOps Engineering
๐ค Artificial Intelligence & Machine Learning
๐ Data Science & Analytics
๐ Cybersecurity
๐ฏ Leadership & Communication
๐๐ป๐ฟ๐ผ๐น๐น ๐๐ผ๐ฟ ๐๐ฅ๐๐๐:-
https://pdlinks.in/i89
Donโt just collect certificates โ build projects, gain practical experience and showcase your skills on your resume & LinkedIn.
โค2
๐ ๐๐ฅ๐๐ ๐๐ฒ๐ป๐๐ + ๐๐น๐ฎ๐๐ฑ๐ฒ ๐ข๐ป๐น๐ถ๐ป๐ฒ ๐ ๐ฎ๐๐๐ฒ๐ฟ๐ฐ๐น๐ฎ๐๐ ๐
Want to work faster, create better content and save hours every week using AI?
Join this beginner-friendly masterclass and discover how to use ๐ฎ๐ฑ+ powerful AI tools to:
โ Automate repetitive tasks
โ Create professional content in minutes
โ Improve productivity and efficiency
โ Save valuable time every week
โ Use GenAI and Claude effectively
๐ก No technical knowledge or previous AI experience required!
๐ ๐ฅ๐ฒ๐ด๐ถ๐๐๐ฒ๐ฟ ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐
https://pdlink.in/46wurp9
โก Limited slots availableโregister now and start working smarter with AI!
Want to work faster, create better content and save hours every week using AI?
Join this beginner-friendly masterclass and discover how to use ๐ฎ๐ฑ+ powerful AI tools to:
โ Automate repetitive tasks
โ Create professional content in minutes
โ Improve productivity and efficiency
โ Save valuable time every week
โ Use GenAI and Claude effectively
๐ก No technical knowledge or previous AI experience required!
๐ ๐ฅ๐ฒ๐ด๐ถ๐๐๐ฒ๐ฟ ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐
https://pdlink.in/46wurp9
โก Limited slots availableโregister now and start working smarter with AI!
๐ SQL Roadmap 2026 โ Part 5
Aggregate Functions: COUNT, SUM, AVG, MIN & MAX ๐
So far, you've learned how to retrieve, filter, and sort individual rows.
Now we're moving to one of the most important skills for a Data Analyst:
For example:
How many customers do we have?
What is our total revenue?
What is the average order value?
What is the highest salary?
What is the lowest product price?
That's exactly what aggregate functions are designed for.
1๏ธโฃ What Are Aggregate Functions?
Aggregate functions perform a calculation across multiple rows and return a summarized result.
The five essential functions are:
โข
โข
โข
โข
โข
2๏ธโฃ COUNT()
Count all rows:
If there are 5,000 customers: total_customers = 5000
3๏ธโฃ COUNT(*) vs COUNT(column)
This distinction is extremely important.
Suppose: employee A | 101, B | 102, C | NULL, D | 103
Then:
Because one manager_id is NULL.
Interview Tip:
4๏ธโฃ COUNT(DISTINCT)
Use
Example:
Suppose: customer_id 101, 101, 102, 103, 103, 103
Then:
This is extremely common in analytics.
5๏ธโฃ Real-World Example: Active Customers
Suppose your orders table contains thousands of orders.
The business asks:
Notice that we're counting customers, not orders. One customer may have placed 20 orders, but should still count as one unique customer.
6๏ธโฃ SUM()
Example:
If the amounts are: 1000, 2000, 1500, 3000 then: SUM = 7500
7๏ธโฃ SUM With a Condition
You can combine
Example:
This is a very common business query.
8๏ธโฃ AVG()
Example:
If salaries are: 50000, 60000, 70000 then: Average = 60000
9๏ธโฃ AVG and NULL Values
Suppose: salary 50000, 60000, NULL, 70000
The average is: (50000 + 60000 + 70000) / 3 = 60000
It doesn't divide by 4. This is important when working with incomplete real-world data.
๐ MIN()
Example:
For products:
Aggregate Functions: COUNT, SUM, AVG, MIN & MAX ๐
So far, you've learned how to retrieve, filter, and sort individual rows.
Now we're moving to one of the most important skills for a Data Analyst:
Turning thousands of rows into meaningful business metrics.
For example:
How many customers do we have?
What is our total revenue?
What is the average order value?
What is the highest salary?
What is the lowest product price?
That's exactly what aggregate functions are designed for.
1๏ธโฃ What Are Aggregate Functions?
Aggregate functions perform a calculation across multiple rows and return a summarized result.
The five essential functions are:
โข
COUNT() Counts rows/valuesโข
SUM() Calculates totalโข
AVG() Calculates averageโข
MIN() Finds minimumโข
MAX() Finds maximum2๏ธโฃ COUNT()
COUNT() is used to count records or non-NULL values.Count all rows:
SELECT COUNT(*) AS total_customers
FROM customers;
If there are 5,000 customers: total_customers = 5000
3๏ธโฃ COUNT(*) vs COUNT(column)
This distinction is extremely important.
COUNT(*) Counts rows.SELECT COUNT(*)
FROM employees;
COUNT(column) Counts non-NULL values in that column.SELECT COUNT(manager_id)
FROM employees;
Suppose: employee A | 101, B | 102, C | NULL, D | 103
Then:
COUNT(*) = 4, COUNT(manager_id) = 3Because one manager_id is NULL.
Interview Tip:
COUNT(*)counts rows;COUNT(column)counts non-NULL values in that column.
4๏ธโฃ COUNT(DISTINCT)
Use
COUNT(DISTINCT ...) when you want to count unique values.Example:
SELECT
COUNT(DISTINCT customer_id) AS unique_customers
FROM orders;
Suppose: customer_id 101, 101, 102, 103, 103, 103
Then:
COUNT(*) = 6, COUNT(DISTINCT customer_id) = 3This is extremely common in analytics.
5๏ธโฃ Real-World Example: Active Customers
Suppose your orders table contains thousands of orders.
The business asks:
How many unique customers placed an order?
SELECT
COUNT(DISTINCT customer_id) AS active_customers
FROM orders;
Notice that we're counting customers, not orders. One customer may have placed 20 orders, but should still count as one unique customer.
6๏ธโฃ SUM()
SUM() calculates the total of a numeric column.Example:
SELECT
SUM(amount) AS total_revenue
FROM orders;
If the amounts are: 1000, 2000, 1500, 3000 then: SUM = 7500
7๏ธโฃ SUM With a Condition
You can combine
SUM() with WHERE.Example:
Calculate revenue from completed orders only.
SELECT
SUM(amount) AS completed_revenue
FROM orders
WHERE order_status = 'Completed';
This is a very common business query.
8๏ธโฃ AVG()
AVG() calculates the average of non-NULL numeric values.Example:
SELECT
AVG(salary) AS average_salary
FROM employees;
If salaries are: 50000, 60000, 70000 then: Average = 60000
9๏ธโฃ AVG and NULL Values
AVG() generally ignores NULL values.Suppose: salary 50000, 60000, NULL, 70000
The average is: (50000 + 60000 + 70000) / 3 = 60000
It doesn't divide by 4. This is important when working with incomplete real-world data.
๐ MIN()
MIN() finds the smallest value.Example:
SELECT
MIN(salary) AS lowest_salary
FROM employees;
For products:
โค4
SELECT
MIN(price) AS lowest_price
FROM products;
1๏ธโฃ1๏ธโฃ MAX()
MAX() finds the largest value.SELECT
MAX(salary) AS highest_salary
FROM employees;
SELECT
MAX(amount) AS largest_order
FROM orders;
1๏ธโฃ2๏ธโฃ Using Multiple Aggregate Functions
You can use several aggregate functions in the same query.
SELECT
COUNT(*) AS total_orders,
SUM(amount) AS total_revenue,
AVG(amount) AS average_order_value,
MIN(amount) AS smallest_order,
MAX(amount) AS largest_order
FROM orders;
This single query gives you a basic sales summary.
1๏ธโฃ3๏ธโฃ Aggregate Functions With WHERE
Example:
Analyze completed orders only.
SELECT
COUNT(*) AS completed_orders,
SUM(amount) AS revenue,
AVG(amount) AS average_order_value,
MIN(amount) AS smallest_order,
MAX(amount) AS largest_order
FROM orders
WHERE order_status = 'Completed';
This is a powerful analytical pattern.
1๏ธโฃ4๏ธโฃ NULL and SUM()
SUM() generally ignores NULL values.Suppose:
amount 1000, 2000, NULL, 3000
Then: SUM(amount) = 6000
However, if all values are NULL, the result can be NULL rather than 0.
You can handle that later using
COALESCE().Example:
SELECT
COALESCE(SUM(amount), 0) AS total_revenue
FROM orders
WHERE order_status = 'Completed';
1๏ธโฃ5๏ธโฃ Aggregate Functions Are the Foundation of KPIs
Most business dashboards are built using aggregate functions.
For example:
โข Revenue =
SUM(amount)โข Number of Orders =
COUNT(*)โข Customers =
COUNT(DISTINCT customer_id)โข Average Order Value =
AVG(amount)โข Largest Order =
MAX(amount)This is why mastering aggregates is critical.
1๏ธโฃ6๏ธโฃ Calculating Average Order Value
A common e-commerce KPI is AOV โ Average Order Value.
A simple version:
SELECT
AVG(amount) AS average_order_value
FROM orders
WHERE order_status = 'Completed';
Another formulation is:
SELECT
SUM(amount) / COUNT(*) AS average_order_value
FROM orders
WHERE order_status = 'Completed';
The
AVG() version is usually clearer when each row represents one order.1๏ธโฃ7๏ธโฃ Calculating Revenue Per Customer
Suppose the business asks:
What is the average revenue generated per unique customer?
You need to be careful not to divide revenue by the number of orders.
SELECT
SUM(amount) /
COUNT(DISTINCT customer_id) AS revenue_per_customer
FROM orders
WHERE order_status = 'Completed';
This is a good example of translating a business metric into SQL.
1๏ธโฃ8๏ธโฃ Aggregate Functions + Expressions
You can aggregate calculations.
Example:
SELECT
SUM(quantity * unit_price) AS total_sales
FROM order_items;
SQL first evaluates:
quantity * unit_price for each row, then sums those values.1๏ธโฃ9๏ธโฃ Aggregate Functions + CASE
You can create conditional metrics.
Example:
SELECT
COUNT(*) AS total_orders,
SUM(
CASE
WHEN order_status = 'Completed'
THEN 1
ELSE 0
END
) AS completed_orders
FROM orders;
This technique becomes extremely important when building dashboards.
2๏ธโฃ0๏ธโฃ Example: Success Rate
Suppose you have payment transactions. You want:
Percentage of successful transactions.
SELECT
100.0 *
SUM(
CASE
WHEN status = 'Success'
THEN 1
ELSE 0
END
) / COUNT(*) AS success_rate
FROM transactions;
This combines: COUNT + SUM + CASE + Arithmetic.
2๏ธโฃ1๏ธโฃ Why GROUP BY Comes Next
At the moment:
SELECT
SUM(amount)
FROM orders;
gives you one total.
But what if the business asks:
What is the revenue for each city?
Now you need:
SELECT
city,
SUM(amount) AS revenue
FROM orders
GROUP BY city;
For now, understand the difference: Aggregate only โ One summary, GROUP BY + Aggregate โ One summary per group
2๏ธโฃ2๏ธโฃ COUNT DISTINCT in Business Analytics
Suppose orders table has 5 orders, customer 101 appears twice, 103 appears twice. Total orders =
COUNT(*) = 5, Unique customers = COUNT(DISTINCT customer_id) = 3. This distinction is fundamental.2๏ธโฃ3๏ธโฃ Common Mistake: COUNT(*) vs COUNT(DISTINCT)
If a customer places multiple orders: Customer 101 โ Order 1, Order 2, Order 3
Then:
COUNT(*) counts: 3 while: COUNT(DISTINCT customer_id) counts: 12๏ธโฃ4๏ธโฃ Real-World Dashboard Query
Imagine your manager asks for a quick sales summary.
SELECT
COUNT(*) AS total_orders,
COUNT(DISTINCT customer_id) AS unique_customers,
SUM(amount) AS total_revenue,
AVG(amount) AS average_order_value,
MIN(amount) AS minimum_order,
MAX(amount) AS maximum_order
FROM orders
WHERE order_status = 'Completed';
This gives you six useful business metrics in one query.
๐ง Common Beginner Mistakes
โ Mistake 1: Counting the wrong thing.
Don't automatically use:
COUNT(*) when the requirement says:
Number of customers. Use:COUNT(DISTINCT customer_id)when appropriate.
โ Mistake 2: Assuming NULL is zero.
NULL โ Missing/unknown, 0 โ Actual numeric zero
โ Mistake 3: Using SUM on text.
SUM() is designed for numeric expressions. This is invalid or inappropriate: SUM(customer_name)โ Mistake 4: Forgetting the business definition.
"Revenue" might mean: Gross revenue, Net revenue, Completed-order revenue, Revenue after discounts, Revenue excluding refunds. Always understand the business definition before writing the SQL.
๐ผ SQL Interview Questions
Q1. What is an aggregate function?
An aggregate function performs a calculation over multiple rows and returns a summarized value.
Q2. Name five common aggregate functions.
COUNT(), SUM(), AVG(), MIN(), MAX()Q3. Difference between
COUNT(*) and COUNT(column)? COUNT(*) counts rows, while COUNT(column) counts non-NULL values in that column.Q4. What does
COUNT(DISTINCT customer_id) do? It counts the number of unique non-NULL customer IDs.
Q5. Does AVG ignore NULL values?
Yes,
AVG() normally ignores NULL values.Q6. How do you calculate total revenue?
SELECT SUM(amount) FROM orders;Q7. How do you find the highest salary?
SELECT MAX(salary) FROM employees;Q8. Can multiple aggregate functions be used together?
Yes.
๐ฏ Practice Questions
Q1. Find the total number of employees.
Q2. Find the average employee salary.
Q3. Find the highest product price.
Q4. Find the lowest product price.
Q5. Calculate total revenue from completed orders.
Q6. Count the number of unique customers who placed an order.
Q7. Find the largest order amount.
Q8. Calculate the average order value for completed orders.
Q9. Count the number of completed orders.
Q10. Calculate total revenue and total unique customers from completed orders.
โ Answers
Answer 1
โค1
SELECT COUNT(*) AS total_employees
FROM employees;
Answer 2
SELECT AVG(salary) AS average_salary
FROM employees;
Answer 3
SELECT MAX(price) AS highest_price
FROM products;
Answer 4
SELECT MIN(price) AS lowest_price
FROM products;
Answer 5
SELECT
SUM(amount) AS total_revenue
FROM orders
WHERE order_status = 'Completed';
Answer 6
SELECT
COUNT(DISTINCT customer_id) AS unique_customers
FROM orders;
Answer 7
SELECT
MAX(amount) AS largest_order
FROM orders;
Answer 8
SELECT
AVG(amount) AS average_order_value
FROM orders
WHERE order_status = 'Completed';
Answer 9
SELECT
COUNT(*) AS completed_orders
FROM orders
WHERE order_status = 'Completed';
Answer 10
SELECT
SUM(amount) AS total_revenue,
COUNT(DISTINCT customer_id) AS unique_customers
FROM orders
WHERE order_status = 'Completed';
๐ฅ Mini Challenge
You have an orders table:
order_id | customer_id | amount | statusBusiness requirement: Calculate: Total completed orders, Unique completed customers, Total completed revenue, Average completed order value, Largest completed order
Solution
SELECT
COUNT(*) AS completed_orders,
COUNT(DISTINCT customer_id) AS unique_customers,
SUM(amount) AS total_revenue,
AVG(amount) AS average_order_value,
MAX(amount) AS largest_order
FROM orders
WHERE status = 'Completed';
Expected result: completed_orders = 4, unique_customers = 3, total_revenue = 15500, average_order_value = 3875, largest_order = 6000
Double Tap โค๏ธ For Part-6
โค4
๐ ๐ ๐ฎ๐๐๐ฒ๐ฟ ๐๐
๐ฐ๐ฒ๐น ๐๐ผ๐ฟ ๐๐ฅ๐๐ | ๐ฑ ๐ฃ๐ผ๐๐ฒ๐ฟ๐ณ๐๐น ๐๐ผ๐๐ฟ๐๐ฒ๐ ๐
๐ฅ Top 5 FREE Excel Courses:
1๏ธโฃ Goldman Sachs โ Excel Skills for Business
2๏ธโฃ PwC โ Problem Solving with Excel
3๏ธโฃ Corporate Finance Institute โ Excel Fundamentals
4๏ธโฃ Great Learning โ Excel for Beginners
5๏ธโฃ Simplilearn โ Introduction to MS Excel
๐๐ป๐ฟ๐ผ๐น๐น ๐๐ผ๐ฟ ๐๐ฅ๐๐๐:-
https://pdlink.in/3UQ8S09
๐ Learn Excel for FREE and upgrade your career skills!
๐ฅ Top 5 FREE Excel Courses:
1๏ธโฃ Goldman Sachs โ Excel Skills for Business
2๏ธโฃ PwC โ Problem Solving with Excel
3๏ธโฃ Corporate Finance Institute โ Excel Fundamentals
4๏ธโฃ Great Learning โ Excel for Beginners
5๏ธโฃ Simplilearn โ Introduction to MS Excel
๐๐ป๐ฟ๐ผ๐น๐น ๐๐ผ๐ฟ ๐๐ฅ๐๐๐:-
https://pdlink.in/3UQ8S09
๐ Learn Excel for FREE and upgrade your career skills!
โค1
๐ ๐๐ฒ๐๐ฒ๐น ๐จ๐ฝ ๐ฌ๐ผ๐๐ฟ ๐๐ฎ๐ฟ๐ฒ๐ฒ๐ฟ ๐๐ถ๐๐ต ๐๐ฅ๐๐ ๐ ๐ถ๐ฐ๐ฟ๐ผ๐๐ผ๐ณ๐ ๐๐ฒ๐ฎ๐ฟ๐ป๐ถ๐ป๐ด! ๐ป
Microsoft-focused learning paths can help you strengthen your resume and prepare for in-demand tech and data roles.
๐ฅ Top 5 Courses / Certification Paths:
โ Beginner-friendly options
โ Build practical, job-ready skills
โ Learn Azure, Power BI, Excel & SQL
โ Strengthen your resume & career profile
๐๐ป๐ฟ๐ผ๐น๐น ๐๐ผ๐ฟ ๐๐ฅ๐๐๐:-
https://pdlink.in/3UNpPs7
๐ซPerfect for students, freshers, data analysts and professionals looking to upgrade their skills.
Microsoft-focused learning paths can help you strengthen your resume and prepare for in-demand tech and data roles.
๐ฅ Top 5 Courses / Certification Paths:
โ Beginner-friendly options
โ Build practical, job-ready skills
โ Learn Azure, Power BI, Excel & SQL
โ Strengthen your resume & career profile
๐๐ป๐ฟ๐ผ๐น๐น ๐๐ผ๐ฟ ๐๐ฅ๐๐๐:-
https://pdlink.in/3UNpPs7
๐ซPerfect for students, freshers, data analysts and professionals looking to upgrade their skills.
โค3
๐ ๐ง๐ผ๐ฝ ๐๐ผ๐บ๐ฝ๐ฎ๐ป๐ถ๐ฒ๐ ๐ข๐ณ๐ณ๐ฒ๐ฟ๐ถ๐ป๐ด ๐๐ฅ๐๐ ๐๐ฒ๐ฟ๐๐ถ๐ณ๐ถ๐ฐ๐ฎ๐๐ถ๐ผ๐ป ๐๐ผ๐๐ฟ๐๐ฒ๐ ๐
Learn in-demand skills โข Add valuable credentials to your resume
๐ข TATA :- https://pdlink.in/3QiwLvx
๐ป Infosys :- https://pdlink.in/4eBH3Aa
โก IBM :- https://pdlink.in/45KgqDR
๐ซ Amazon :- https://pdlink.in/47XuBGz
๐ Cisco :- https://pdlink.in/4gaeVVV
๐ช Microsoft :- https://pdlink.in/4zhGTX6
๐ข Save & share this with your friends โ start upskilling for FREE!
Learn in-demand skills โข Add valuable credentials to your resume
๐ข TATA :- https://pdlink.in/3QiwLvx
๐ป Infosys :- https://pdlink.in/4eBH3Aa
โก IBM :- https://pdlink.in/45KgqDR
๐ซ Amazon :- https://pdlink.in/47XuBGz
๐ Cisco :- https://pdlink.in/4gaeVVV
๐ช Microsoft :- https://pdlink.in/4zhGTX6
๐ข Save & share this with your friends โ start upskilling for FREE!
๐ SQL Roadmap 2026 โ Part 6
GROUP BY & HAVING โ Analyzing Data by Categories ๐
In Part 5, you learned how aggregate functions answer questions like:
But real-world business questions are usually more specific:
That's where GROUP BY comes in.
1๏ธโฃ What is GROUP BY?
GROUP BY combines rows with the same value into groups so that aggregate functions can calculate a metric for each group.
Basic Syntax
Example:
Instead of getting one total employee count, you get a count for each department.
2๏ธโฃ Why Do We Need GROUP BY?
Without GROUP BY:
Result: 1000
This answers: How many employees are there?
But:
Result:
โข IT | 350
โข Finance | 200
โข HR | 120
โข Sales | 330
Now you can answer: How many employees are in each department?
3๏ธโฃ GROUP BY With COUNT()
This is probably the most common GROUP BY pattern.
4๏ธโฃ GROUP BY With SUM()
Suppose you want revenue by city.
This is a common business KPI.
5๏ธโฃ GROUP BY With AVG()
Calculate average salary by department:
6๏ธโฃ GROUP BY With MIN() and MAX()
You can use multiple aggregate functions.
7๏ธโฃ Multiple Aggregations
You aren't limited to one metric.
This is the foundation of many analytical reports.
8๏ธโฃ GROUP BY Multiple Columns
You can group by more than one column.
Example: Count customers by city and customer segment.
SQL creates a group for each unique combination.
9๏ธโฃ Understanding Multiple GROUP BY Columns
Grouping by
โข Mumbai + Premium
โข Mumbai + Standard
โข Delhi + Premium
The combination matters.
๐ GROUP BY With WHERE
WHERE filters rows before grouping.
Example: Calculate revenue by city for completed orders only.
Conceptually: All Orders โ WHERE Completed โ GROUP BY City โ SUM Revenue
1๏ธโฃ1๏ธโฃ WHERE vs GROUP BY
WHERE Answers: Which rows should be included?
GROUP BY Answers: How should those rows be divided into groups?
1๏ธโฃ2๏ธโฃ What is HAVING?
HAVING filters groups after aggregation.
Example: Find departments with more than 100 employees.
GROUP BY & HAVING โ Analyzing Data by Categories ๐
In Part 5, you learned how aggregate functions answer questions like:
What is the total revenue?
How many customers do we have?
But real-world business questions are usually more specific:
What is the revenue by city?
How many employees are there in each department?
Which products generated the most revenue?
That's where GROUP BY comes in.
1๏ธโฃ What is GROUP BY?
GROUP BY combines rows with the same value into groups so that aggregate functions can calculate a metric for each group.
Basic Syntax
SELECT
column_name,
aggregate_function(column)
FROM table_name
GROUP BY column_name;
Example:
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department;
Instead of getting one total employee count, you get a count for each department.
2๏ธโฃ Why Do We Need GROUP BY?
Without GROUP BY:
SELECT COUNT(*) AS total_employees
FROM employees;
Result: 1000
This answers: How many employees are there?
But:
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department;
Result:
โข IT | 350
โข Finance | 200
โข HR | 120
โข Sales | 330
Now you can answer: How many employees are in each department?
3๏ธโฃ GROUP BY With COUNT()
This is probably the most common GROUP BY pattern.
SELECT
city,
COUNT(*) AS customer_count
FROM customers
GROUP BY city;
4๏ธโฃ GROUP BY With SUM()
Suppose you want revenue by city.
SELECT
city,
SUM(amount) AS total_revenue
FROM orders
GROUP BY city;
This is a common business KPI.
5๏ธโฃ GROUP BY With AVG()
Calculate average salary by department:
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department;
6๏ธโฃ GROUP BY With MIN() and MAX()
You can use multiple aggregate functions.
SELECT
department,
MIN(salary) AS minimum_salary,
MAX(salary) AS maximum_salary,
AVG(salary) AS average_salary
FROM employees
GROUP BY department;
7๏ธโฃ Multiple Aggregations
You aren't limited to one metric.
SELECT
department,
COUNT(*) AS employees,
SUM(salary) AS total_salary,
AVG(salary) AS average_salary,
MIN(salary) AS minimum_salary,
MAX(salary) AS maximum_salary
FROM employees
GROUP BY department;
This is the foundation of many analytical reports.
8๏ธโฃ GROUP BY Multiple Columns
You can group by more than one column.
Example: Count customers by city and customer segment.
SELECT
city,
customer_segment,
COUNT(*) AS customer_count
FROM customers
GROUP BY
city,
customer_segment;
SQL creates a group for each unique combination.
9๏ธโฃ Understanding Multiple GROUP BY Columns
Grouping by
GROUP BY city, segment creates groups like:โข Mumbai + Premium
โข Mumbai + Standard
โข Delhi + Premium
The combination matters.
๐ GROUP BY With WHERE
WHERE filters rows before grouping.
Example: Calculate revenue by city for completed orders only.
SELECT
city,
SUM(amount) AS revenue
FROM orders
WHERE order_status = 'Completed'
GROUP BY city;
Conceptually: All Orders โ WHERE Completed โ GROUP BY City โ SUM Revenue
1๏ธโฃ1๏ธโฃ WHERE vs GROUP BY
WHERE Answers: Which rows should be included?
GROUP BY Answers: How should those rows be divided into groups?
1๏ธโฃ2๏ธโฃ What is HAVING?
HAVING filters groups after aggregation.
Example: Find departments with more than 100 employees.
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 100;
1๏ธโฃ3๏ธโฃ WHERE vs HAVING
This is one of the most frequently asked SQL interview questions.
WHERE filters individual rows.
WHERE salary > 500000HAVING filters groups.
HAVING AVG(salary) > 800000Remember:
WHERE โ Filter rows
GROUP BY โ Create groups
HAVING โ Filter groups
1๏ธโฃ4๏ธโฃ Example: WHERE + GROUP BY + HAVING
Requirement: Find departments whose average salary is greater than โน8 lakh, considering only employees earning more than โน5 lakh.
SELECT
department,
AVG(salary) AS average_salary
FROM employees
WHERE salary > 500000
GROUP BY department
HAVING AVG(salary) > 800000;
1๏ธโฃ5๏ธโฃ GROUP BY With COUNT(DISTINCT)
Very useful for customer analytics.
SELECT
DATE_TRUNC('month', order_date) AS month,
COUNT(DISTINCT customer_id) AS unique_customers
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;
1๏ธโฃ6๏ธโฃ GROUP BY With CASE
You can create business categories and then group them.
SELECT
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END AS salary_band,
COUNT(*) AS employee_count
FROM employees
GROUP BY
CASE
WHEN salary >= 1000000 THEN 'High'
WHEN salary >= 600000 THEN 'Medium'
ELSE 'Low'
END;
1๏ธโฃ7๏ธโฃ GROUP BY Dates
This is extremely important for Data Analysts.
Example: Calculate monthly revenue.
SELECT
DATE_TRUNC('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;
1๏ธโฃ8๏ธโฃ Daily Sales
SELECT
order_date,
SUM(amount) AS daily_revenue
FROM orders
GROUP BY order_date
ORDER BY order_date;
1๏ธโฃ9๏ธโฃ Monthly Order Count
SELECT
DATE_TRUNC('month', order_date) AS month,
COUNT(*) AS order_count
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;
2๏ธโฃ0๏ธโฃ Monthly Customer Count
SELECT
DATE_TRUNC('month', order_date) AS month,
COUNT(DISTINCT customer_id) AS active_customers
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;
Notice:
COUNT(*) counts orders, while COUNT(DISTINCT customer_id) counts unique customers.2๏ธโฃ1๏ธโฃ GROUP BY With ORDER BY
Example: Find departments with the highest average salary.
SELECT
department,
AVG(salary) AS average_salary
FROM employees
GROUP BY department
ORDER BY average_salary DESC;
2๏ธโฃ2๏ธโฃ GROUP BY + HAVING + ORDER BY
A powerful analytical pattern:
SELECT
customer_id,
SUM(amount) AS total_spend
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 50000
ORDER BY total_spend DESC;
2๏ธโฃ3๏ธโฃ Real-World Example: Top Revenue Categories
Requirement: Find categories generating more than โน10 lakh in revenue.
SELECT
p.category,
SUM(oi.quantity * oi.selling_price) AS revenue
FROM products p
JOIN order_items oi
ON p.product_id = oi.product_id
GROUP BY p.category
HAVING SUM(oi.quantity * oi.selling_price) > 1000000
ORDER BY revenue DESC;
2๏ธโฃ4๏ธโฃ Common GROUP BY Error
SELECT
department,
employee_name,
AVG(salary)
FROM employees
GROUP BY department;
โค2
This is generally invalid because
2๏ธโฃ5๏ธโฃ The Golden Rule of GROUP BY
When using GROUP BY, every selected expression generally needs to be either:
1. Included in GROUP BY
2. Or aggregated
Think: Group columns describe the group; aggregate functions summarize the group.
2๏ธโฃ6๏ธโฃ SQL Query Pattern to Memorize
Example:
๐ง Logical Processing Order
A useful simplified model is:
FROM โ WHERE โ GROUP BY โ HAVING โ SELECT โ ORDER BY โ LIMIT
This helps explain why
๐ผ SQL Interview Questions
Q1. What is GROUP BY?
Groups rows with the same values so aggregate functions can calculate metrics for each group.
Q2. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping, while HAVING filters groups after aggregation.
Q3. Can GROUP BY contain multiple columns?
Yes.
Q4. Can GROUP BY be used without an aggregate function?
Yes, although
Q5. Can you use aggregate functions in WHERE?
Generally no. Use HAVING.
Q6. Why do we use COUNT(DISTINCT customer_id)?
To count unique customers rather than counting every transaction.
๐ฏ Practice Questions
Q1. Count employees in each department.
Q2. Calculate total revenue by product category.
Q3. Calculate average salary by department.
Q4. Find the highest salary in each department.
Q5. Count customers by city.
Q6. Find cities with more than 500 customers.
Q7. Calculate monthly revenue.
Q8. Calculate monthly unique customers.
Q9. Find customers whose total spending is greater than โน50,000.
Q10. Find product categories generating more than โน1 lakh revenue, sorted from highest to lowest.
โ Answers
Answer 1
Answer 2
Answer 3
Answer 4
Answer 5
Answer 6
Answer 7
Answer 8
Answer 9
Answer 10
employee_name is neither grouped, nor aggregated.2๏ธโฃ5๏ธโฃ The Golden Rule of GROUP BY
When using GROUP BY, every selected expression generally needs to be either:
1. Included in GROUP BY
2. Or aggregated
Think: Group columns describe the group; aggregate functions summarize the group.
2๏ธโฃ6๏ธโฃ SQL Query Pattern to Memorize
SELECT
grouping_column,
AGGREGATE_FUNCTION(value_column) AS metric
FROM table_name
WHERE row_condition
GROUP BY grouping_column
HAVING group_condition
ORDER BY metric DESC;
Example:
SELECT
city,
SUM(amount) AS revenue
FROM orders
WHERE order_status = 'Completed'
GROUP BY city
HAVING SUM(amount) > 100000
ORDER BY revenue DESC;
๐ง Logical Processing Order
A useful simplified model is:
FROM โ WHERE โ GROUP BY โ HAVING โ SELECT โ ORDER BY โ LIMIT
This helps explain why
WHERE SUM(amount) > 100000 is not valid. Use HAVING instead.๐ผ SQL Interview Questions
Q1. What is GROUP BY?
Groups rows with the same values so aggregate functions can calculate metrics for each group.
Q2. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping, while HAVING filters groups after aggregation.
Q3. Can GROUP BY contain multiple columns?
Yes.
GROUP BY city, category;Q4. Can GROUP BY be used without an aggregate function?
Yes, although
SELECT DISTINCT is often clearer when the goal is simply to return unique combinations.Q5. Can you use aggregate functions in WHERE?
Generally no. Use HAVING.
Q6. Why do we use COUNT(DISTINCT customer_id)?
To count unique customers rather than counting every transaction.
๐ฏ Practice Questions
Q1. Count employees in each department.
Q2. Calculate total revenue by product category.
Q3. Calculate average salary by department.
Q4. Find the highest salary in each department.
Q5. Count customers by city.
Q6. Find cities with more than 500 customers.
Q7. Calculate monthly revenue.
Q8. Calculate monthly unique customers.
Q9. Find customers whose total spending is greater than โน50,000.
Q10. Find product categories generating more than โน1 lakh revenue, sorted from highest to lowest.
โ Answers
Answer 1
SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY department;
Answer 2
SELECT category, SUM(amount) AS revenue FROM sales GROUP BY category;
Answer 3
SELECT department, AVG(salary) AS average_salary FROM employees GROUP BY department;
Answer 4
SELECT department, MAX(salary) AS highest_salary FROM employees GROUP BY department;
Answer 5
SELECT city, COUNT(*) AS customer_count FROM customers GROUP BY city;
Answer 6
SELECT city, COUNT(*) AS customer_count
FROM customers GROUP BY city HAVING COUNT(*) > 500;
Answer 7
SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue FROM orders GROUP BY DATE_TRUNC('month', order_date) ORDER BY month;Answer 8
SELECT DATE_TRUNC('month', order_date) AS month, COUNT(DISTINCT customer_id) AS unique_customers FROM orders GROUP BY DATE_TRUNC('month', order_date) ORDER BY month;Answer 9
SELECT customer_id, SUM(amount) AS total_spend FROM orders GROUP BY customer_id HAVING SUM(amount) > 50000 ORDER BY total_spend DESC;
Answer 10
SELECT category, SUM(amount) AS revenue FROM sales GROUP BY category HAVING SUM(amount) > 100000 ORDER BY revenue DESC;
โค1
๐ฅ Mini Challenge
You have orders table with columns:
Find each city's: Completed order count, Unique customers, Total revenue, Average order value. Only include cities where completed revenue is greater than โน10,000. Sort by revenue from highest to lowest.
Solution:
Double Tap โค๏ธ For Part-7
You have orders table with columns:
order_id, customer_id, city, amount, statusFind each city's: Completed order count, Unique customers, Total revenue, Average order value. Only include cities where completed revenue is greater than โน10,000. Sort by revenue from highest to lowest.
Solution:
SELECT
city,
COUNT(*) AS completed_orders,
COUNT(DISTINCT customer_id) AS unique_customers,
SUM(amount) AS revenue,
AVG(amount) AS average_order_value
FROM orders
WHERE status = 'Completed'
GROUP BY city
HAVING SUM(amount) > 10000
ORDER BY revenue DESC;
Double Tap โค๏ธ For Part-7
โค4
๐ ๐๐ฟ๐ฒ๐ฎ๐บ๐ถ๐ป๐ด ๐ผ๐ณ ๐ช๐ผ๐ฟ๐ธ๐ถ๐ป๐ด ๐ฎ๐ ๐ง๐ผ๐ฝ ๐ง๐ฒ๐ฐ๐ต ๐๐ผ๐บ๐ฝ๐ฎ๐ป๐ถ๐ฒ๐? ๐ป๐ฅ
Hereโs a collection of company-specific resources to help you understand their interview and hiring processes.
๐ฏ Interview Preparation Guides For:
๐ Amazon โ Interviewing Guide
๐ต Google โ Interview Tips
๐ช Microsoft โ Hiring & Interview Tips
๐ข NVIDIA โ Hiring Process
๐ท Meta โ Software Engineering Interview Prep
๐๐ข๐ง๐ค ๐:-
https://pdlink.in/4i6HkgN
๐ข Save & share this with your friends โ start learning for FREE!
Hereโs a collection of company-specific resources to help you understand their interview and hiring processes.
๐ฏ Interview Preparation Guides For:
๐ Amazon โ Interviewing Guide
๐ต Google โ Interview Tips
๐ช Microsoft โ Hiring & Interview Tips
๐ข NVIDIA โ Hiring Process
๐ท Meta โ Software Engineering Interview Prep
๐๐ข๐ง๐ค ๐:-
https://pdlink.in/4i6HkgN
๐ข Save & share this with your friends โ start learning for FREE!
โค5
๐ฅ ๐ ๐ฎ๐๐๐ฒ๐ฟ ๐ฆ๐ค๐ ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ โ ๐๐ฟ๐ผ๐บ ๐๐ฒ๐ด๐ถ๐ป๐ป๐ฒ๐ฟ ๐๐ผ ๐๐ฑ๐๐ฎ๐ป๐ฐ๐ฒ๐ฑ! ๐ป๐
These free learning resources cover everything from database fundamentals to advanced SQL queries, with opportunities to practice real-world problems.
๐ฏ Top FREE SQL Resources:
1๏ธโฃ Introduction to Databases & SQL โ Udemy
2๏ธโฃ Advanced Database & SQL โ Udemy
3๏ธโฃ Learn SQL โ Codecademy
4๏ธโฃ SQL Tutorial โ SQLZoo
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlink.in/4gNYHk7
๐ Start from the basics and work your way toward advanced SQL skills!
These free learning resources cover everything from database fundamentals to advanced SQL queries, with opportunities to practice real-world problems.
๐ฏ Top FREE SQL Resources:
1๏ธโฃ Introduction to Databases & SQL โ Udemy
2๏ธโฃ Advanced Database & SQL โ Udemy
3๏ธโฃ Learn SQL โ Codecademy
4๏ธโฃ SQL Tutorial โ SQLZoo
๐ ๐๐ป๐ฟ๐ผ๐น๐น ๐ณ๐ผ๐ฟ ๐๐ฅ๐๐ ๐:-
https://pdlink.in/4gNYHk7
๐ Start from the basics and work your way toward advanced SQL skills!