Fixed Top Ad (Local Preview)800x90 โ€ข Slot 6608427872

Intermediate SQL

โœ•

1. Subquery and CTE

    1.1 ๐Ÿ” What is a Subquery?
    1. A subquery is a query written inside another query. It is useful when we want to solve a problem in multiple steps. Example idea: First find customers from Kathmandu. Then find transactions made by those customers.
    1.2 Subquery Example
    1. SELECT * FROM transaction_details WHERE customer_id IN (SELECT idFROM customerWHERE address = 'Kathmandu' ); Here: SELECT id FROM customer WHERE address = 'Kathmandu' runs first. Then the outer query finds transactions for those customer IDs. ๐Ÿ“Œ Idea: A subquery lets one query use the result of another query.

2. Common Table Expression

    2.1 ๐Ÿงฉ What is a CTE?
    1. CTE means Common Table Expression. A CTE is a temporary named result set that we can use later in the same query. It helps make complex SQL queries easier to read.
    2.2 CTE Syntax
    1. WITH cte_name AS (SELECT ... ) SELECT ... FROM cte_name;
    2.3 CTE Example
    1. WITH ktm_customer AS (SELECT id AS customer_idFROM customerWHERE address = 'Kathmandu' )SELECT * FROM transaction_details WHERE customer_id IN (SELECT customer_idFROM ktm_customer ); ๐Ÿ“Œ Idea: A CTE is like giving a name to a temporary result so we can use it later.
2.4 Subquery vs CTE
FeatureSubqueryCTE
Where it is writtenInside another queryBefore the main query
ReadabilityGood for small logicBetter for complex logic
Reuse in same queryHarderEasier
Keyword usedNo special keywordWITH
CTE vs Subquery
CTE vs Subquery

3. Aggregation, Grouping, and HAVING

    3.1 ๐Ÿ“Š What is Aggregation?
    1. Aggregation means summarizing many rows into one result. This is similar to NumPy aggregate functions like: ๐Ÿ‘‰ sum ๐Ÿ‘‰ mean ๐Ÿ‘‰ min ๐Ÿ‘‰ max
Common Aggregate Functions
FunctionMeaning
COUNT()Count rows
SUM()Total value
AVG()Average value
MIN()Minimum value
MAX()Maximum value
SQL Aggregate Functions
    3.2 Aggregate Examples
    1. Count total transactions: SELECT COUNT(*) AS total_txn FROM transaction_details; Find total salary: SELECT SUM(salary) AS total_salary FROM employee; Find average product price: SELECT AVG(price) AS avg_price FROM product; Find minimum and maximum salary: SELECTMIN(salary) AS min_salary,MAX(salary) AS max_salary FROM employee; ๐Ÿ“Œ Simple idea: Aggregate functions summarize data.

4. GROUP BY

    4.1 ๐Ÿงบ What is GROUP BY?
    1. GROUP BY is used when we want summary results for each group. Example: Find average salary for each department.
    4.2 GROUP BY Example
    1. SELECTdepartment,AVG(salary) AS avg_salary FROM employee GROUP BY department; This groups employees by department and calculates average salary for each department. ๐Ÿ“Œ Simple idea: GROUP BY creates groups, then aggregate functions summarize each group.
    4.3 GROUP BY Multiple Columns
    1. We can also group by more than one column. SELECTbrand,name,COUNT(*) AS product_count FROM product GROUP BY brand, name; ๐Ÿ“Œ This groups data by both brand and name.
SQL GROUP BY

5. HAVING

    5.1 ๐ŸŽฏ What is HAVING?
    1. HAVING is used to filter groups after aggregation. Example: Show only departments where average salary is greater than 50000.
    5.2 HAVING Example
    1. SELECTdepartment,AVG(salary) AS avg_salary FROM employee GROUP BY department HAVING AVG(salary) > 50000; ๐Ÿ“Œ Simple idea: WHERE filters rows before grouping. HAVING filters groups after grouping.
5.3 WHERE vs HAVING
ClauseUsed ForWorks Before or After Aggregation
WHEREFiltering rowsBefore aggregation
HAVINGFiltering grouped resultsAfter aggregation
    5.4 Example with both
    1. SELECTdepartment,AVG(salary) AS avg_salary FROM employee WHERE is_active = TRUE GROUP BY department HAVING AVG(salary) > 50000; Here: WHERE is_active = TRUE filters employees first GROUP BY department groups remaining employees HAVING AVG(salary) > 50000 filters the grouped result
Difference between WHERE and HAVING
Difference between WHERE and HAVING

6. Joining Multiple Tables

    6.1 ๐Ÿ”— What is a JOIN?
    1. A JOIN is used to combine data from multiple tables. Example: transaction_details stores transaction data customer stores customer details employee stores employee or cashier details product stores product details Using joins, we can create one result that combines information from all these tables. ๐Ÿ“Œ Simple idea: JOIN helps us look up related information from different tables.
    6.2 Why Do We Join Tables?
    1. We join tables when one table has IDs and another table has details. Example: transaction_details columns: customer_id, product_id, cashier_id customer columns: id, name, address So we connect: transaction_details.customer_id = customer.id

7. Types of SQL Joins

7.1 Join Types
Join TypeMeaning
INNER JOINReturns rows that match in both tables
LEFT JOINReturns all rows from the left table and matching rows from the right table
RIGHT JOINReturns all rows from the right table and matching rows from the left table
FULL OUTER JOINReturns all rows from both tables
CROSS JOINReturns all possible combinations
SELF JOINJoins a table with itself
    7.2 INNER JOIN
    1. INNER JOIN returns only matching rows from both tables. SELECTt.id,c.name AS customer_name,t.txn_date FROM transaction_details t INNER JOIN customer c ON t.customer_id = c.id; ๐Ÿ“Œ If a customer does not match, that transaction will not appear.
    7.3 LEFT JOIN
    1. LEFT JOIN returns all rows from the left table. If there is no match in the right table, it shows NULL. SELECTt.id,c.name AS customer_name,t.txn_date FROM transaction_details t LEFT JOIN customer c ON t.customer_id = c.id; ๐Ÿ“Œ Simple idea: Keep everything from the left table.
    7.4 RIGHT JOIN
    1. RIGHT JOIN returns all rows from the right table. SELECTt.id,c.name AS customer_name,t.txn_date FROM transaction_details t RIGHT JOIN customer c ON t.customer_id = c.id; ๐Ÿ“Œ Simple idea: Keep everything from the right table.
    7.5 FULL OUTER JOIN
    1. FULL OUTER JOIN returns all rows from both tables. SELECTt.id,c.name AS customer_name,t.txn_date FROM transaction_details t FULL OUTER JOIN customer c ON t.customer_id = c.id; ๐Ÿ“Œ If a row does not match, missing values appear as NULL.
    7.6 CROSS JOIN
    1. CROSS JOIN gives all possible combinations of rows. SELECTc.name AS customer_name,p.name AS product_name FROM customer c CROSS JOIN product p; ๐Ÿ“Œ Be careful: CROSS JOIN can create many rows quickly.
    7.7 SELF JOIN
    1. A SELF JOIN means joining a table with itself. Example: Employees table has manager_id, and we want to find each employee's manager. SELECTe.name AS employee_name,m.name AS manager_name FROM employee e LEFT JOIN employee m ON e.manager_id = m.id; ๐Ÿ“Œ Simple idea: SELF JOIN compares rows inside the same table.

8. Example of Joining Multiple Tables

    8.1 Joining Transaction, Customer, Employee, and Product
    1. SELECTc.name AS customer_name,e.name AS employee_name,p.name AS product_name,t.product_qty,t.txn_date FROM transaction_details t LEFT JOIN customer c ON t.customer_id = c.id LEFT JOIN employee e ON t.cashier_id = e.id LEFT JOIN product p ON t.product_id = p.id; This query combines: - Customer name from customer - Employee name from employee - Product name from product - Quantity and date from transaction_details ๐Ÿ“Œ Simple idea: One table stores IDs. Other tables explain what those IDs mean.

9. Overall SQL Query Order

    9.1 Full Query Structure
    1. SELECT ... FROM table_name JOIN table_name ON condition WHERE condition GROUP BY columns HAVING condition ORDER BY columns LIMIT number;
    9.2 Important Rule
    1. We can skip clauses we do not need, but if we use them, they should follow this order: SELECT โ†’ FROM โ†’ JOIN โ†’ WHERE โ†’ GROUP BY โ†’ HAVING โ†’ ORDER BY โ†’ LIMIT ๐Ÿ“Œ SQL clauses must be written in the proper order.
Order of SQL Syntax
Order of SQL Syntax

10. SET Operations

    10.1 ๐Ÿงฎ What are SET Operations?
    1. SET operations combine the results of two or more SELECT statements. They are useful when we want to compare or combine similar results.
10.2 Common SET Operations
OperationMeaning
UNIONCombines results and removes duplicates
UNION ALLCombines results and keeps duplicates
INTERSECTReturns only common rows from both results
EXCEPTReturns rows from the first result that are not in the second result
    10.3 Important Rule
    1. For SET operations, both SELECT queries should return: - Same number of columns - Compatible data types - Same column order ๐Ÿ“Œ Simple idea: SET operations stack query results on top of each other.

11. SET Operation Examples

    11.1 UNION
    1. SELECT name FROM customer WHERE address = 'Kathmandu'UNIONSELECT name FROM employee WHERE department = 'HR'; ๐Ÿ“Œ UNION removes duplicate names.
What are SQL Set Operations?
SQL Set Operations
    11.2 UNION ALL
    1. SELECT name FROM customer WHERE address = 'Kathmandu'UNION ALLSELECT name FROM employee WHERE department = 'HR'; ๐Ÿ“Œ UNION ALL keeps duplicate names.
    11.3 INTERSECT
    1. SELECT name FROM customer WHERE address = 'Kathmandu'INTERSECTSELECT name FROM employee WHERE department = 'HR'; ๐Ÿ“Œ INTERSECT returns names found in both results.
    11.4 EXCEPT
    1. SELECT name FROM customer WHERE address = 'Kathmandu'EXCEPTSELECT name FROM employee WHERE department = 'HR'; ๐Ÿ“Œ EXCEPT returns names from the first result that are not in the second result.

12. What's Next?

    12.1 Upcoming Topics
    1. After this lesson, we can learn: - Window functions - Recursive CTE - Performance tuning - More SQL functions
Ad PlaceholderSlot: 7421026683

Practice QuestionsNot started

  1. Aggregation

    Question 1 of 3

      Write SQL queries to answer the following questions:
      1. How many customers are registered with the mart?
      2. Find the record of the employee who earns the second-highest salary. [Hint: use offset]
      3. Find the total salary expenditure for the mart. [Note: Consider only active employees.]
      4. How many customers does the mart have in each city? [Display the city name and the customer count.]
      5. Calculate the average salary of employees in each department.
      6. Write a query to detect whether the same email address is used by multiple customers. [i.e., display email with count > 1]
      7. On which day did the mart offer the highest total discount? [Hint: First sum the discount for each day, then identify the day with the highest total.].
      8. Find the number of active employees in each department.
  2. Joining / SubQuery

    Question 2 of 3

      Write SQL queries to answer the following questions:
      1. Find the total discount amount received by each customer. [Note: Groupby CustomerID as name can repeat]
      2. Show the customer name, product name, cashier name, and quantity for each transaction made by customers from Kathmandu after 2025.
      3. Find the total number of transactions handled by each employee in July, 2025.
      4. For each product, find total transaction, total quantity sold, Total transaction amount (without discount) and total discount.
      5. Find customers who have made more than 20 transactions.
      6. List employees who have not handled any transactions.
      7. Find products that have never been sold.
      8. Show the record of employee who handled the highest number of transactions.
      9. List transactions where the discount was more than 50% of the product's unit price.
      10. Find the first transaction date for each customer.
      11. Find the top 3 customers based on total reward points. [Hint: First sum and then use order by]
      12. Find customers whose first transaction occurred before their registration date.
      13. Find the average spending per customer.
      14. List each employee along with their manager's name.
      15. Identify inactive employees who have performed transactions.
      16. Find customers who have never purchased a Smartphone. [Note: Use Subqyery, think why not in does not work here]
      17. Find the top 5 most popular brands selling Organic Apple based on the total quantity sold.
  3. Set Operations

    Question 3 of 3

      Write SQL queries to answer the following questions:
      1. Find the ID, name, and email of customers who made transactions in June 2025 but not in July 2025.
      2. Find the ID, name, and email of customers who made transactions in either June 2025 or July 2025.
      3. Find the ID, name, and email of customers who made transactions in both June 2025 and July 2025.
Ad PlaceholderSlot: 5413242224