Intermediate SQL

Subquery, Common Table Expression (CTE)

    Subquery
    1. A query nested inside another query.
    2. Used to perform operations in multiple steps.
    3. Example SELECT * FROM transaction WHERE customer_id IN ( SELECT id FROM customer WHERE address = 'Kathmandu');
    CTE (Common Table Expression)
    1. Temporary named result set that we can reference later.
    2. Improves readability and modularity of complex queries.
    3. Example WITH ktm_customer AS ( SELECT id AS customer_id FROM customer WHERE address = 'Kathmandu') SELECT * FROM transaction WHERE customer_id IN (SELECT customer_id FROM ktm_customer);

Aggregation, Grouping and HAVING

  • Similar to what we learn in NumPy, aggregate functions
  • Compute summary statistics across groups of records.
  • Common Functions: COUNT, SUM, AVG, MIN, MAX.
  • GROUP BY is used to compute aggregates for each group.
  • HAVING is used to filter groups after aggregation.
  • Example:
    1. SELECT COUNT(*) AS total_txn FROM transaction;
    2. SELECT SUM(salary) AS total_salary FROM employee;
    3. SELECT AVG(price) AS avg_price FROM product WHERE category = 'Electronics';
    4. SELECT category, AVG(price) AS avg_price FROM product GROUP BY category;
    5. SELECT department, AVG(salary) AS avg_salary FROM employee GROUP BY 1 HAVING AVG(salary) > 50000;
    6. SELECT brand, name, COUNT(*) FROM product GROUP BY 1, 2 HAVING COUNT(*) < 5;

Joining Multiple Tables

  • For lookup and find information across tables.
  • Referential columns with foreign key constraints are used for joining tables.
  • Sample Doc with JOIN explanation.
Types of SQL Joins:
Join TypeDescription
INNER JOINReturns records that have matching values in both tables.
LEFT JOINReturns all records from the left table, and the matched records from the right table. If there is no match, the result is NULL on the right side.
RIGHT JOINReturns all records from the right table, and the matched records from the left table. If there is no match, the result is NULL on the left side.
FULL OUTER JOINReturns all records when there is a match in either left or right table. If there is no match, the result is NULL on the side that does not have a match.
CROSS JOINReturns the Cartesian product of the two tables, i.e., all possible combinations of records from both tables.
SELF JOINA regular join but the table is joined with itself. Used to compare rows within the same table.
Examples of different types of SQL joins

SQL JOIN Types

Visual representation of different SQL joins
Visual representation of different SQL joins

Example of Joining Multiple Tables

  • SELECT c.name AS customer_name , e.name AS employee_name , p.name AS product_name , t.product_qty, t.txn_date FROM transaction t [LEFT|RIGHT|CROSS|FULL|INNER] JOIN customer c ON t.customer_id = c.id JOIN employee e ON t.employee_id = e.id JOIN product p ON t.product_id = p.id;

Overall Syntax

  • SELECT... FROM JOIN ... ON ... ... ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT ...;
  • NOTE: We can skip any of the above clauses if not needed. But if used order of syntax has to be same as above.

SET Operations

  • Used to combine results of two or more SELECT statements.
Common SQL Set Operations:
OperationDescription
UNIONCombines results of two SELECT statements and removes duplicates.
UNION ALLCombines results of two SELECT statements and includes duplicates.
INTERSECTReturns only the records that are common to both SELECT statements.
EXCEPTReturns records from the first SELECT statement that are not in the second SELECT statement.
Examples of common SQL set operations

Set Operation Examples

  • SELECT name FROM customer WHERE address = 'Kathmandu' UNION SELECT name FROM employee WHERE department = 'HR';
  • SELECT name FROM customer WHERE address = 'Kathmandu' UNION ALL SELECT name FROM employee WHERE department = 'HR';
  • SELECT name FROM customer WHERE address = 'Kathmandu' INTERSECT SELECT name FROM employee WHERE department = 'HR';
  • SELECT name FROM customer WHERE address = 'Kathmandu' EXCEPT SELECT name FROM employee WHERE department = 'HR';

What's Next?

  • Window Functions
  • Recursive CTE
  • Performance Tuning
  • Common Functions of SQL

Practice QuestionsNot started

  1. Aggregation

    Question 1 of 3

    • Get the total number of customers.
    • Find employee that gets second highest salary. [Hint: use offset]
    • Find total expenditure on salary by mart on 3 month.
    • Total total number of customer on each city.
    • Calculate the average salary of employees in each department.
    • Write a query to detect if same email is reused by multiple customer.
    • On which day, highest discount was given by mart.
    • Find number of active employee across each department.
  2. Joining / SubQuery

    Question 2 of 3

    • Find the total discount amount given per customer.
    • Show customer name, product name, cashier name, quantity for each transaction done by user of kathmandu after 2025.
    • Find the total transaction, monetory value handled by each employee in july.
    • For each product, find total transaction, total item sold, txn amount (without discount) & total discount.
    • Find customers who have made more than 20 transactions.
    • List employees who haven't handled any transaction.
    • Find products that were never sold.
    • Show the employee who handled the highest number of transactions.
    • List transactions where the discount was more than 50% of the product's unit price.
    • Find the first transaction date for each customer.
    • Find the top 3 customers based on total reward points.
    • Find customers whose first transaction happened before registration.
    • List customers who purchased the same product more than once.
    • Find average spending per customer.
    • List employee name and their manager's name.
    • Identify if an inactive employee has performed transactions.
    • Find customer who haven't bought any Smartphone.
    • Find top 5 most popular brand that sells Organic Apple based on qty sold.
    • List name, address of employee who have never received discount.
    • Find list of churn customer in 2025, June. [Txn on May but not in june]
    • Find customer who bought notebook on May & June but yet to buy on July.
  3. Set Operations

    Question 3 of 3

    • Find id, name, email of customers doing transactions in 2025 June but not in July.
    • Find id, name, email of customers doing transactions in 2025 June or July.
    • Find id, name, email ofcustomers doing transactions in 2025 June and July.