Intermediate SQL concepts are used to write more advanced queries, handle NULL values, combine data from multiple tables, and break complex queries into simpler steps.
CASE WHEN is a conditional expression in SQL used to apply conditions and return different values based on those conditions. It works like IF-ELSE statements in programming languages.
SELECT column_name,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result
END AS alias_name
FROM table_name;
-- Categorize employees based on salary
SELECT name, salary,
CASE
WHEN salary >= 60000 THEN 'High Salary'
WHEN salary >= 45000 THEN 'Medium Salary'
ELSE 'Low Salary'
END AS salary_category
FROM employees;
Output:
| name | salary | salary_category |
|---|---|---|
| Aarav | 60000 | High Salary |
| Priya | 45000 | Medium Salary |
| Rohan | 55000 | Medium Salary |
| Sneha | 70000 | High Salary |
| Karan | 40000 | Low Salary |
| Anjali | 65000 | High Salary |
-- Identify employees based on department
SELECT name, department,
CASE
WHEN department = 'IT' THEN 'Technology Team'
WHEN department = 'HR' THEN 'Human Resources Team'
ELSE 'Other Department'
END AS department_category
FROM employees;
CASE WHENworks like IF-ELSE or conditional statements in programming.WHENspecifies the condition.THENspecifies the result when the condition is true.ELSEspecifies the default result when no condition matches.ENDmarks the end of the CASE expression.ELSEis optional. If omitted and no condition matches, SQL returnsNULL.- Conditions are checked from top to bottom. The first matching condition is executed.
CASEcan be used withSELECT,ORDER BY,GROUP BY, and aggregate functions.
IFNULL() and COALESCE() are used to handle NULL values in SQL by replacing them with another value.
| Function | Purpose |
|---|---|
IFNULL() |
Returns an alternative value if the expression is NULL. |
COALESCE() |
Returns the first non-NULL value from a list of expressions. |
Definition: IFNULL() checks whether a value is NULL. If it is NULL, it returns the replacement value; otherwise, it returns the original value.
Syntax
SELECT IFNULL(expression, alternative_value)
FROM table_name;
Example
-- Replace NULL manager IDs with 0
SELECT name, IFNULL(manager_id, 0) AS manager_id
FROM employees;
Output:
| name | manager_id |
|---|---|
| Aarav | 0 |
| Priya | 1 |
| Rohan | 1 |
| Sneha | 1 |
| Karan | 2 |
| Anjali | 1 |
Definition: COALESCE() returns the first non-NULL value from a list of expressions. If all expressions are NULL, it returns NULL.
Syntax
SELECT COALESCE(value1, value2, value3, ...)
FROM table_name;
Example
-- Return the first available value
SELECT COALESCE(NULL, NULL, 'Available', 'Not Available')
AS result;
Output: Available
-- Use COALESCE to replace NULL manager IDs
SELECT name, COALESCE(manager_id, 0) AS manager_id
FROM employees;
| IFNULL() | COALESCE() |
|---|---|
| Takes exactly two arguments. | Accepts two or more arguments. |
| Checks one expression for NULL. | Checks multiple expressions. |
| Commonly used in MySQL and SQLite. | Supported by major SQL databases. |
| Returns the alternative value if NULL. | Returns the first non-NULL value. |
IFNULL()is commonly used in MySQL and SQLite; SQL Server usesISNULL()instead.COALESCE()is part of standard SQL and is supported by MySQL, PostgreSQL, SQL Server, and Oracle.COALESCE()evaluates values from left to right.- If all values are NULL,
COALESCE()returns NULL. - Replacement values should have compatible data types.
- These functions are useful when displaying reports and handling missing database values.
JOINs are used to combine rows from two or more tables based on a related column between them.
They help retrieve related information stored in different tables.
| JOIN | Purpose |
|---|---|
| INNER JOIN | Returns matching records from both tables. |
| LEFT JOIN | Returns all records from the left table and matching records from the right table. |
| RIGHT JOIN | Returns all records from the right table and matching records from the left table. |
| FULL OUTER JOIN | Returns matching and non-matching records from both tables. |
| CROSS JOIN | Returns every possible combination of rows. |
| SELF JOIN | Joins a table with itself. |
Table 1: employees
| emp_id | name | department_id |
|---|---|---|
| 1 | Aarav | 101 |
| 2 | Priya | 102 |
| 3 | Rohan | 101 |
| 4 | Sneha | 103 |
| 5 | Karan | 104 |
Table 2: departments
| department_id | department_name |
|---|---|
| 101 | IT |
| 102 | HR |
| 103 | Finance |
| 105 | Marketing |
Note: These are separate example tables created specifically to understand JOINs.
Definition: Returns only the records that have matching values in both tables.
Syntax
SELECT columns
FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;
Example
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.department_id;
Output:
| name | department_name |
|---|---|
| Aarav | IT |
| Priya | HR |
| Rohan | IT |
| Sneha | Finance |
Definition: Returns all records from the left table and matching records from the right table. If there is no match, NULL values are returned for the right table's columns.
Syntax
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;
Example
SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;
Output:
| name | department_name |
|---|---|
| Aarav | IT |
| Priya | HR |
| Rohan | IT |
| Sneha | Finance |
| Karan | NULL |
Definition: Returns all records from the right table and matching records from the left table. If there is no match, NULL values are returned for the left table's columns.
Syntax
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;
Example
SELECT employees.name, departments.department_name
FROM employees
RIGHT JOIN departments
ON employees.department_id = departments.department_id;
Output:
| name | department_name |
|---|---|
| Aarav | IT |
| Priya | HR |
| Rohan | IT |
| Sneha | Finance |
| NULL | Marketing |
Definition: Returns all records from both tables, including matching and non-matching records. Non-matching columns are filled with NULL.
Syntax
SELECT columns
FROM table1
FULL OUTER JOIN table2
ON table1.common_column = table2.common_column;
Example
SELECT employees.name, departments.department_name
FROM employees
FULL OUTER JOIN departments
ON employees.department_id = departments.department_id;
Output:
| name | department_name |
|---|---|
| Aarav | IT |
| Priya | HR |
| Rohan | IT |
| Sneha | Finance |
| Karan | NULL |
| NULL | Marketing |
Note: MySQL does not directly support FULL OUTER JOIN. It can be simulated using LEFT JOIN, RIGHT JOIN, and UNION.
Definition: Returns the Cartesian product of two tables, meaning every row from the first table is combined with every row from the second table.
Syntax
SELECT columns
FROM table1
CROSS JOIN table2;
Example
SELECT employees.name, departments.department_name
FROM employees
CROSS JOIN departments;
Output: Since the first table contains 5 rows and the second contains 4 rows, the result contains:
5 × 4 = 20 rows
Definition: A SELF JOIN is used to join a table with itself. It is useful when records in a table are related to other records in the same table.
Syntax
SELECT a.column_name, b.column_name
FROM table_name a
JOIN table_name b
ON a.common_column = b.common_column;
Example
Using the original employees table, each employee has a manager_id that refers to another employee's emp_id.
-- Display employee names with their manager names
SELECT
e.name AS employee_name,
m.name AS manager_name
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.emp_id;
Output:
| employee_name | manager_name |
|---|---|
| Aarav | NULL |
| Priya | Aarav |
| Rohan | Aarav |
| Sneha | Aarav |
| Karan | Priya |
| Anjali | Aarav |
- JOINs combine related data from multiple tables.
- The
ONclause specifies the matching condition. INNER JOINreturns only matching records.LEFT JOINpreserves every row from the left table.RIGHT JOINpreserves every row from the right table.FULL OUTER JOINpreserves rows from both tables.CROSS JOINproduces a Cartesian product.SELF JOINuses aliases to refer to the same table twice.- Always use table aliases (
e,d) to make complex JOIN queries easier to read. - MySQL supports INNER, LEFT, RIGHT, CROSS, and SELF JOINs, but not native FULL OUTER JOIN.
- JOINs are especially important in data analytics because information is often stored across multiple related tables.
A Subquery is a query written inside another SQL query. It is also called an inner query or nested query.
The outer query uses the result returned by the inner query.
SELECT column_name
FROM table_name
WHERE column_name operator (
SELECT column_name
FROM table_name
);
-- Find employees earning more than the average salary
SELECT name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
Output:
| name | salary |
|---|---|
| Aarav | 60000 |
| Sneha | 70000 |
| Anjali | 65000 |
| Type | Description |
|---|---|
| Single-row subquery | Returns only one row. |
| Multiple-row subquery | Returns multiple rows. |
| Multiple-column subquery | Returns multiple columns. |
| Correlated subquery | Depends on the outer query for its execution. |
| Nested subquery | Contains another subquery inside it. |
1. Subquery with IN
-- Find employees working in departments having more than one employee
SELECT name, department
FROM employees
WHERE department IN (
SELECT department
FROM employees
GROUP BY department
HAVING COUNT(*) > 1
);
2. Subquery with MAX()
-- Find the employee receiving the highest salary
SELECT name, salary
FROM employees
WHERE salary = (
SELECT MAX(salary)
FROM employees
);
3. Correlated Subquery
-- Find employees earning more than their department's average salary
SELECT e.name, e.department, e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department = e.department
);
- A subquery is enclosed within parentheses
(). - The inner query executes to provide a result to the outer query.
- Subqueries can be used with
SELECT,INSERT,UPDATE, andDELETE. - Use
INwhen the subquery returns multiple values. - Use comparison operators such as
=,>, and<when the subquery returns a single value. EXISTSchecks whether a subquery returns at least one row.- Correlated subqueries refer to columns from the outer query.
- Subqueries can be used with aggregate functions such as
SUM(),AVG(),MIN(), andMAX().
A Common Table Expression (CTE) is a temporary named result set that exists only during the execution of a single SQL statement.
It is defined using the WITH keyword and makes complex queries easier to read, understand, and maintain.
WITH cte_name AS (
SELECT column_name
FROM table_name
WHERE condition
)
SELECT *
FROM cte_name;
-- Find employees earning more than 50000
WITH high_salary AS (
SELECT name, salary
FROM employees
WHERE salary > 50000
)
SELECT *
FROM high_salary;
Output:
| name | salary |
|---|---|
| Aarav | 60000 |
| Rohan | 55000 |
| Sneha | 70000 |
| Anjali | 65000 |
1. CTE with Aggregate Functions
-- Calculate average salary department-wise
WITH department_salary AS (
SELECT department, AVG(salary) AS average_salary
FROM employees
GROUP BY department
)
SELECT *
FROM department_salary;
2. CTE with WHERE
-- Find employees earning more than the average salary
WITH average_salary AS (
SELECT AVG(salary) AS avg_salary
FROM employees
)
SELECT name, salary
FROM employees
WHERE salary > (
SELECT avg_salary
FROM average_salary
);
3. Multiple CTEs
-- Create two temporary result sets
WITH department_count AS (
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
),
department_salary AS (
SELECT department, AVG(salary) AS average_salary
FROM employees
GROUP BY department
)
SELECT
dc.department,
dc.total_employees,
ds.average_salary
FROM department_count dc
JOIN department_salary ds
ON dc.department = ds.department;
| Type | Description |
|---|---|
| Non-recursive CTE | A normal CTE that does not refer to itself. |
| Recursive CTE | A CTE that refers to itself to process hierarchical or repeated data. |
Definition: A Recursive CTE is a CTE that repeatedly references itself to process hierarchical or sequential data until a termination condition is met.
Example
-- Generate numbers from 1 to 5
WITH RECURSIVE numbers AS (
SELECT 1 AS num
UNION ALL
SELECT num + 1
FROM numbers
WHERE num < 5
)
SELECT * FROM numbers;
Output:
| num |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
- CTEs are defined using the
WITHkeyword. - A CTE exists only for the duration of a single SQL statement.
- CTEs make complex queries more readable and organized.
- Multiple CTEs can be defined in one query, separated by commas.
- Recursive CTEs are useful for hierarchical data such as employee-manager relationships.
- A CTE does not automatically create a permanent database table.
- CTEs can be used with SELECT, INSERT, UPDATE, and DELETE statements, depending on database support.
- MySQL 8.0 and later support CTEs.
- Recursive CTEs require a termination condition to avoid endless recursion.
| Subquery | CTE |
|---|---|
| A query inside another query. | A named temporary result set. |
| Written inside parentheses. | Defined using the WITH keyword. |
| Can become difficult to read when deeply nested. | Makes complex queries easier to organize. |
| Usually used for a specific nested operation. | Can be referenced multiple times within the same statement. |
| Can be correlated. | Can be recursive. |
- Categorize employees as High, Medium, or Low salary based on their salary.
- Display employee names and assign a category based on their department.
- Display employee names and show 'Manager' if
manager_idis NULL, otherwise show 'Employee'.
- Replace NULL values in
manager_idwith 0 usingIFNULL(). - Use
COALESCE()to return the first available value from three expressions. - Display employee names and manager IDs, replacing NULL manager IDs with 'No Manager'.
- Display employee names along with their department names using INNER JOIN.
- Display all employees, including those without a matching department, using LEFT JOIN.
- Display all departments, including those without employees, using RIGHT JOIN.
- Display all matching and non-matching records from both tables.
- Generate all possible combinations of employees and departments using CROSS JOIN.
- Display employee names along with their manager names using SELF JOIN.
- Find employees earning more than the average salary.
- Find the employee receiving the highest salary using a subquery.
- Find employees working in departments having more than one employee.
- Find employees earning more than their department's average salary.
- Find employees who earn the second-highest distinct salary.
- Create a CTE to display employees earning more than 50000.
- Create a CTE to calculate the average salary of each department.
- Create two CTEs to calculate employee count and average salary department-wise.
- Use a recursive CTE to generate numbers from 1 to 10.
- Use a CTE to find employees earning more than the company's average salary.
Author: Priya Yadav — Learning, practicing, and improving one query at a time.