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 productwhere→ keep matching rowsselect→ pick the columns

All examples below run against this instructor table:

IDnamedept_namesalary
1AbdurCSE10000
2amanCSE12500
3bilalCSE17000
4morshedEEE12000
5rashidBBA10000
6irshadBBA7800
6 tuples · 4 attributes

The select clause

  • SELECT * = all attributes; names are case-insensitive (Name = name).
  • Duplicates are kept by default — use DISTINCT to drop them.
  • Arithmetic + AS to rename the output column.
Task

List each department once.

sql
SELECT distinct dept_name
FROM instructor;
Result
dept_name
CSE
EEE
BBA
3 tuples · 1 attribute
Task

Show a daily-rate column.

sql
SELECT id, name, salary/30
       AS daily_salary
FROM instructor;
Result
IDnamedaily_salary
1Abdur333.33
2aman416.67
3bilal566.67
4morshed400
5rashid333.33
6irshad260
6 tuples · 3 attributes

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
IDname
2aman
3bilal
2 tuples · 2 attributes

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-key

The 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
namec_id
Abdurcse100
bilalcse303
morshedeee100
rashidcse400
irshadbba200
5 tuples · 2 attributes

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