Skip to content

Latest commit

 

History

History
675 lines (543 loc) · 17.3 KB

03-sql-intermediate-sql.md

File metadata and controls

675 lines (543 loc) · 17.3 KB

12. INTERMEDIATE SQL

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.


12.1 CASE WHEN

Definition

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.

Syntax

SELECT column_name,
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ELSE result
END AS alias_name
FROM table_name;

Example

-- 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

Additional Example

-- 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;

Important Points:-

  • CASE WHEN works like IF-ELSE or conditional statements in programming.
  • WHEN specifies the condition.
  • THEN specifies the result when the condition is true.
  • ELSE specifies the default result when no condition matches.
  • END marks the end of the CASE expression.
  • ELSE is optional. If omitted and no condition matches, SQL returns NULL.
  • Conditions are checked from top to bottom. The first matching condition is executed.
  • CASE can be used with SELECT, ORDER BY, GROUP BY, and aggregate functions.

12.2 IFNULL() AND COALESCE()

Definition

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.

1. IFNULL()

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

2. COALESCE()

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

Additional Example

-- Use COALESCE to replace NULL manager IDs
SELECT name, COALESCE(manager_id, 0) AS manager_id
FROM employees;

Difference Between IFNULL() and COALESCE()

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.

Important Points:-

  • IFNULL() is commonly used in MySQL and SQLite; SQL Server uses ISNULL() 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.

12.3 JOINS IN SQL

Definition

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.

Types of JOINS

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.

Practice Table for JOINs

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.

1. INNER JOIN

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

2. LEFT JOIN

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

3. RIGHT JOIN

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

4. FULL OUTER JOIN

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.

5. CROSS JOIN

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

6. SELF JOIN

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

Important Points:-

  • JOINs combine related data from multiple tables.
  • The ON clause specifies the matching condition.
  • INNER JOIN returns only matching records.
  • LEFT JOIN preserves every row from the left table.
  • RIGHT JOIN preserves every row from the right table.
  • FULL OUTER JOIN preserves rows from both tables.
  • CROSS JOIN produces a Cartesian product.
  • SELF JOIN uses 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.

12.4 SUBQUERIES

Definition

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.

Syntax

SELECT column_name
FROM table_name
WHERE column_name operator (
    SELECT column_name
    FROM table_name
);

Example

-- 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

Types of Subqueries

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.

Additional Examples

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
);

Important Points:-

  • 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, and DELETE.
  • Use IN when the subquery returns multiple values.
  • Use comparison operators such as =, >, and < when the subquery returns a single value.
  • EXISTS checks 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(), and MAX().

12.5 COMMON TABLE EXPRESSIONS (CTEs)

Definition

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.

Syntax

WITH cte_name AS (
    SELECT column_name
    FROM table_name
    WHERE condition
)
SELECT *
FROM cte_name;

Example

-- 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

Additional Examples

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;

Types of CTEs

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.

Recursive CTE

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

Important Points:-

  • CTEs are defined using the WITH keyword.
  • 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.

DIFFERENCE BETWEEN SUBQUERY AND CTE

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.

PRACTICE QUESTIONS (Solve These!)

CASE WHEN

  1. Categorize employees as High, Medium, or Low salary based on their salary.
  2. Display employee names and assign a category based on their department.
  3. Display employee names and show 'Manager' if manager_id is NULL, otherwise show 'Employee'.

IFNULL() AND COALESCE()

  1. Replace NULL values in manager_id with 0 using IFNULL().
  2. Use COALESCE() to return the first available value from three expressions.
  3. Display employee names and manager IDs, replacing NULL manager IDs with 'No Manager'.

JOINS

  1. Display employee names along with their department names using INNER JOIN.
  2. Display all employees, including those without a matching department, using LEFT JOIN.
  3. Display all departments, including those without employees, using RIGHT JOIN.
  4. Display all matching and non-matching records from both tables.
  5. Generate all possible combinations of employees and departments using CROSS JOIN.
  6. Display employee names along with their manager names using SELF JOIN.

SUBQUERIES

  1. Find employees earning more than the average salary.
  2. Find the employee receiving the highest salary using a subquery.
  3. Find employees working in departments having more than one employee.
  4. Find employees earning more than their department's average salary.
  5. Find employees who earn the second-highest distinct salary.

CTEs

  1. Create a CTE to display employees earning more than 50000.
  2. Create a CTE to calculate the average salary of each department.
  3. Create two CTEs to calculate employee count and average salary department-wise.
  4. Use a recursive CTE to generate numbers from 1 to 10.
  5. 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.