SELECT–FROM–WHERE
Lecture 4 · the heart of SQL. Every query is a select … from … where …, and its result is always a relation.
Basic query structure
select A1, A2, ..., An -- the columns you want (π projection)
from r1, r2, ..., rm -- the relations involved (× product)
where P; -- the condition (σ selection)from→ build the product›where→ keep matching rows›select→ pick the columns
All examples below run against this instructor table:
| ID | name | dept_name | salary |
|---|---|---|---|
| 1 | Abdur | CSE | 10000 |
| 2 | aman | CSE | 12500 |
| 3 | bilal | CSE | 17000 |
| 4 | morshed | EEE | 12000 |
| 5 | rashid | BBA | 10000 |
| 6 | irshad | BBA | 7800 |
The select clause
SELECT *= all attributes; names are case-insensitive (Name = name).- Duplicates are kept by default — use
DISTINCTto drop them. - Arithmetic +
ASto rename the output column.
Task
List each department once.
sql
SELECT distinct dept_name
FROM instructor;↓ Result
| dept_name |
|---|
| CSE |
| EEE |
| BBA |
Task
Show a daily-rate column.
sql
SELECT id, name, salary/30
AS daily_salary
FROM instructor;↓ Result
| ID | name | daily_salary |
|---|---|---|
| 1 | Abdur | 333.33 |
| 2 | aman | 416.67 |
| 3 | bilal | 566.67 |
| 4 | morshed | 400 |
| 5 | rashid | 333.33 |
| 6 | irshad | 260 |
The where clause & predicates
Task
Find CSE instructors earning more than 10000.
sql
SELECT id, name
FROM instructor
WHERE dept_name = 'CSE' AND salary > 10000;
-- range shorthand:
-- WHERE salary BETWEEN 11000 AND 100000;↓ Result Abdur is exactly 10000, so he's excluded
| ID | name |
|---|---|
| 2 | aman |
| 3 | bilal |
String matching — LIKE
%any substring (incl. empty)_exactly one character'Intro%'anything starting with “Intro”'%Comp%'contains “Comp”'_ _ _'exactly three characters'100 \%'literal “100%” (\ escapes)SELECT name FROM instructor WHERE name LIKE '%ras%'; -- names containing 'ras'Patterns are case-sensitive. SQL also has || concatenation, upper/lower, length, substring, etc.
Ordering — ORDER BY
SELECT distinct name FROM instructor ORDER BY name; -- asc is default
SELECT * FROM instructor ORDER BY dept_name, name DESC; -- multi-keyThe from clause & joins
from A, B is the Cartesian product — every pair. On its own it's rarely useful; add a where join condition to keep only matching pairs:
Task
Names of instructors who taught some course, with the course id.
sql
SELECT name, c_id
FROM instructor, courseAllocation
WHERE instructor.ID = courseAllocation.ID;↓ Result joined instructor.ID = courseAllocation.ID
| name | c_id |
|---|---|
| Abdur | cse100 |
| bilal | cse303 |
| morshed | eee100 |
| rashid | cse400 |
| irshad | bba200 |
Self-join via rename (AS)
Rename a table to use it twice — e.g. instructors earning more than some CSE instructor:
SELECT distinct T.name
FROM instructor AS T, instructor AS S
WHERE T.salary > S.salary AND S.dept_name = 'CSE'; -- 'as' is optional