SQL (Structured Query Language) is how you talk to a relational database — a set of tables, each a grid of rows (records) and columns (fields). You describe what data you want and the database works out how to get it. The workhorse is the SELECT statement.
The sample database
Every example in this book uses the same small company database — departments, employees and projects. Learn it once and you can follow every query that follows.
Our sample schema and data
-- departments dept_id | dept_name | location 10 | Engineering | Bengaluru 20 | Sales | Mumbai 30 | HR | Pune -- employees emp_id | name | dept_id | salary | manager_id | hire_date 1 | Asha | 10 | 90000 | NULL | 2019-03-01 2 | Ravi | 10 | 60000 | 1 | 2021-06-15 3 | Meena | 20 | 75000 | 1 | 2020-01-20 4 | John | 20 | 50000 | 3 | 2022-09-10 5 | Priya | 30 | 55000 | 1 | 2021-11-05 6 | Sam | 10 | 60000 | 1 | 2023-02-01 -- projects proj_id | proj_name | dept_id | budget 101 | Apollo | 10 | 500000 102 | Orion | 20 | 300000 103 | Helix | 10 | 150000
The basic SELECT
Pick columns from a table
SELECT name, salary -- columns you want FROM employees; -- table to read from SELECT * -- all columns FROM departments;
DISTINCT, ORDER BY and LIMIT
SELECT DISTINCT dept_id -- unique values only FROM employees; SELECT name, salary FROM employees ORDER BY salary DESC -- highest first LIMIT 3; -- only the top 3 rows
⚡ The edge
- SELECT chooses columns, FROM chooses the table. Use SELECT * only while exploring — in real queries, name the columns so the result is stable and readable.
- ORDER BY defaults to ascending; add DESC for descending. Pair it with LIMIT (or TOP in SQL Server) to get 'the top N' rows.
Worked example
List the three highest-paid employees, showing only their name and salary.
- Choose the columns: name and salary.
- Sort by salary, highest first: ORDER BY salary DESC.
- Keep only the first three rows: LIMIT 3.
Answer: SELECT name, salary FROM employees ORDER BY salary DESC LIMIT 3;
Worked example
How many distinct departments do employees belong to?
- You want unique department values, so use DISTINCT on dept_id.
- To count them, combine COUNT with DISTINCT.
- The query is COUNT(DISTINCT dept_id).
Answer: SELECT COUNT(DISTINCT dept_id) FROM employees; -- returns 3
⚠ Watch out
- SELECT * is convenient but fragile — column order/additions can break code that depends on it.
- ORDER BY is ascending by default; don't assume descending.
- Top-N syntax differs by dialect: LIMIT n (MySQL/Postgres) vs TOP n (SQL Server).