Skip to content
Chethan Yadav_
Database Management Systems

DBMS/Lesson 4 of 9/6 min read

SQL

SQL query structure and execution order, joins, aggregation with GROUP BY and HAVING, subqueries, set operations, views, stored procedures, triggers, window functions, and common interview queries.


On this page

SQL

SQL (Structured Query Language) is the declarative language for relational databases. You describe the result; the optimizer chooses how to compute it.

Example schema used below:

employee(id, name, dept_id, salary, manager_id)
department(id, name)

Query structure and logical execution order

SELECT   dept_id, COUNT(*) AS n
FROM     employee
WHERE    salary > 50000
GROUP BY dept_id
HAVING   COUNT(*) > 3
ORDER BY n DESC
LIMIT    5;

Written order differs from the logical evaluation order:

  1. FROM / JOIN
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT (window functions run here)
  6. DISTINCT
  7. ORDER BY
  8. LIMIT / OFFSET

That is why a column alias from SELECT cannot be used in WHERE, but can be used in ORDER BY.

SQL Joins

Joins combine rows from two tables based on a related column.

Inner Join

Only rows with a match in both tables.

SELECT e.name, d.name AS dept
FROM employee e
INNER JOIN department d ON e.dept_id = d.id;

Left Join

All rows from the left table, plus matches from the right; NULL where no match.

-- employees without a department
SELECT e.name
FROM employee e
LEFT JOIN department d ON e.dept_id = d.id
WHERE d.id IS NULL;
  • Right join: all rows from the right table.
  • Full outer join: all rows from both, NULL where missing.
  • Cross join: Cartesian product, m * n rows.

Self Join

A table joined with itself, used for hierarchies:

SELECT e.name AS employee, m.name AS manager
FROM employee e
LEFT JOIN employee m ON e.manager_id = m.id;

Aggregation

Aggregate functions: COUNT, SUM, AVG, MIN, MAX. COUNT(*) counts rows; COUNT(col) skips NULLs.

GROUP BY

Groups rows with the same values so aggregates are computed per group. Every non-aggregated column in SELECT must be in GROUP BY.

HAVING

Filters groups after aggregation. WHERE filters rows before grouping.

SELECT dept_id, AVG(salary)
FROM employee
GROUP BY dept_id
HAVING AVG(salary) > 60000;

Subquery

A subquery is a query nested inside another.

-- employees earning more than the company average
SELECT name FROM employee
WHERE salary > (SELECT AVG(salary) FROM employee);

Operators: IN, NOT IN, EXISTS, ANY, ALL.

NOT IN with a subquery that returns any NULL yields no rows, because x <> NULL is unknown. Prefer NOT EXISTS.

Correlated Subquery

A correlated subquery references the outer query and runs once per outer row.

-- employees earning more than their department average
SELECT e.name FROM employee e
WHERE e.salary > (
  SELECT AVG(salary) FROM employee WHERE dept_id = e.dept_id
);

Set operations

  • UNION: combine results, remove duplicates.
  • UNION ALL: keep duplicates (faster).
  • INTERSECT, EXCEPT (MINUS in Oracle).

CTE

A Common Table Expression (WITH) names a temporary result for readability. Recursive CTEs walk hierarchies:

WITH RECURSIVE chain AS (
  SELECT id, name, manager_id FROM employee WHERE id = 7
  UNION ALL
  SELECT e.id, e.name, e.manager_id
  FROM employee e JOIN chain c ON e.id = c.manager_id
)
SELECT * FROM chain;   -- employee 7 and all managers above

Window Function

A window function computes across related rows without collapsing them (unlike GROUP BY).

SELECT name, dept_id, salary,
  RANK()       OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk,
  DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS drnk,
  ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rn,
  SUM(salary)  OVER (PARTITION BY dept_id) AS dept_total,
  LAG(salary)  OVER (ORDER BY id) AS prev_salary
FROM employee;

For salaries 100, 100, 90: ROW_NUMBER = 1, 2, 3; RANK = 1, 1, 3; DENSE_RANK = 1, 1, 2.

View

A view is a named stored query that acts as a virtual table. It stores no data.

CREATE VIEW high_earners AS
SELECT name, salary FROM employee WHERE salary > 100000;

Uses: simplify complex queries, security (expose only some columns), logical data independence. Simple views over one table can be updatable.

Materialized View

A materialized view stores the query result physically and must be refreshed. Fast reads, stale data between refreshes. Used for reporting and dashboards.

Stored Procedure

A stored procedure is precompiled SQL (with control flow) stored in the database and invoked by name.

CREATE PROCEDURE give_raise(IN p_dept INT, IN pct DECIMAL)
BEGIN
  UPDATE employee SET salary = salary * (1 + pct / 100) WHERE dept_id = p_dept;
END;

Benefits: fewer round trips, reuse, security (grant execute only). A function returns a value and can be used inside queries; a procedure is called with CALL.

Trigger

A trigger runs automatically on INSERT, UPDATE or DELETE, BEFORE or AFTER the event, per row or per statement.

CREATE TRIGGER audit_salary
AFTER UPDATE OF salary ON employee
FOR EACH ROW
INSERT INTO salary_audit(emp_id, old_salary, new_salary)
VALUES (OLD.id, OLD.salary, NEW.salary);

Use for auditing and enforcing complex rules. Overuse hides logic and slows writes.

Constraints in SQL

PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, DEFAULT. See keys and integrity.

Common interview queries

Second highest salary:

SELECT MAX(salary) FROM employee
WHERE salary < (SELECT MAX(salary) FROM employee);
 
-- Nth highest (N = 3)
SELECT DISTINCT salary FROM employee
ORDER BY salary DESC LIMIT 1 OFFSET 2;

Find duplicate emails:

SELECT email, COUNT(*) FROM users
GROUP BY email HAVING COUNT(*) > 1;

Delete duplicates, keep the lowest id:

DELETE FROM users u
USING users u2
WHERE u.email = u2.email AND u.id > u2.id;   -- PostgreSQL syntax

Top earner per department:

SELECT * FROM (
  SELECT e.*, RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) r
  FROM employee e
) t WHERE r = 1;

Quick revision

  • Logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.
  • WHERE filters rows, HAVING filters groups.
  • LEFT JOIN + IS NULL finds missing matches.
  • Window functions keep rows; GROUP BY collapses them.
  • Avoid NOT IN with nullable subqueries.