Intermediate SQL
✕Subquery, Common Table Expression (CTE)
- A query nested inside another query.
- Used to perform operations in multiple steps.
- Example
SELECT * FROM transaction WHERE customer_id IN ( SELECT id FROM customer WHERE address = 'Kathmandu'); - Temporary named result set that we can reference later.
- Improves readability and modularity of complex queries.
- 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);
Subquery
CTE (Common Table Expression)
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. SELECT COUNT(*) AS total_txn FROM transaction;SELECT SUM(salary) AS total_salary FROM employee;SELECT AVG(price) AS avg_price FROM product WHERE category = 'Electronics';SELECT category, AVG(price) AS avg_price FROM product GROUP BY category;SELECT department, AVG(salary) AS avg_salary FROM employee GROUP BY 1 HAVING AVG(salary) > 50000;SELECT brand, name, COUNT(*) FROM product GROUP BY 1, 2 HAVING COUNT(*) < 5;
Example:
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 Type | Description |
|---|---|
| INNER JOIN | Returns records that have matching values in both tables. |
| LEFT JOIN | Returns 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 JOIN | Returns 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 JOIN | Returns 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 JOIN | Returns the Cartesian product of the two tables, i.e., all possible combinations of records from both tables. |
| SELF JOIN | A 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

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 skipany of the above clauses if not needed. But if usedorderof syntax hasto be sameas above.
SET Operations
- Used to combine results of two or more SELECT statements.
Common SQL Set Operations:
| Operation | Description |
|---|---|
| UNION | Combines results of two SELECT statements and removes duplicates. |
| UNION ALL | Combines results of two SELECT statements and includes duplicates. |
| INTERSECT | Returns only the records that are common to both SELECT statements. |
| EXCEPT | Returns 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
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.
Joining / SubQuery
Question 2 of 3
- Find the total discount amount given per customer.
- Show
customer name,product name,cashier name,quantityfor each transaction done by user of kathmandu after 2025. - Find the
total transaction,monetory valuehandled 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.
Set Operations
Question 3 of 3
- Find
id,name,emailof customers doing transactions in 2025 June but not in July. - Find
id,name,emailof customers doing transactions in 2025 June or July. - Find
id,name,emailofcustomers doing transactions in 2025 June and July.
- Find
