Sub topic 14
SQL basics: SELECT, WHERE, DISTINCT and duplicates
This chapter assumes you know the relational model (relations, tuples, attributes), selection and projection in relational algebra, and basic set theory. You do not need prior SQL experience. By the end you will be able to read a SELECT-FROM-WHERE query, translate it to relational algebra, and predict how many rows it returns when duplicates are present.
The running schema
All examples use this schema, the same one used in the rest of the tutorial.
Student(sid, sname, age)
Course(cid, cname)
Enrolled(sid, cid)The SELECT-FROM-WHERE block
The basic SQL query has three clauses.
FROMnames the input tables.WHEREkeeps only the rows that satisfy a condition.SELECTchooses which columns appear in the output.
The query for students older than 20 looks like this.
SELECT DISTINCT sname
FROM Student
WHERE age > 20;The clauses are written in the order SELECT, FROM, WHERE. They are evaluated in a different order: FROM first, then WHERE, then SELECT. This matters because the WHERE clause cannot refer to a name that SELECT defines, such as a column alias.
The query maps to relational algebra as follows.
π_sname (σ_age > 20 (Student))WHERE corresponds to selection (σ). The SELECT list corresponds to projection (π). Note the naming trap: the SQL word SELECT corresponds to projection, not to the algebra operator σ.
The same query in tuple relational calculus is:
{ t | ∃s ∈ Student (s.age > 20 ∧ t.sname = s.sname) }Sets versus bags
Relational algebra works on sets. A relation never contains two identical tuples. SQL tables and query results are bags (also called multisets). A bag can contain the same row more than once.
This is the most common source of wrong answers in exam questions. Consider the table below.
| sid | sname | age |
|---|---|---|
| 1 | Asha | 21 |
| 2 | Ravi | 22 |
| 3 | Asha | 23 |
Run the query without DISTINCT.
SELECT sname
FROM Student
WHERE age > 20;All three rows pass the WHERE condition, and the projection to sname keeps all three. The result is Asha, Ravi, Asha: three rows. The relational algebra expression πsname(σage>20(Student)) returns only two tuples, Asha and Ravi, because projection removes duplicates.
SELECT DISTINCT removes duplicate rows from the result and restores set behavior.
SELECT DISTINCT sname
FROM Student
WHERE age > 20;This returns two rows.
When duplicates appear
Duplicates appear when the projected columns do not include a key. If the SELECT list contains a candidate key of the table, every output row is distinct because each source row has a different key value. Projecting only sname can create duplicates because sname is not a key.
Duplicates can also come from joins. If a student is enrolled in three courses and you project only sname from the join of Student and Enrolled, that name appears three times.
SELECT s.sname
FROM Student s, Enrolled e
WHERE s.sid = e.sid;The number of rows equals the number of matching (student, enrollment) pairs, not the number of students.
Cost of DISTINCT
DISTINCT is not free. The system must sort or hash the result to find duplicates. Use it when the question requires set semantics, and avoid it when the output is already guaranteed to be distinct, for example when a key is in the SELECT list.
The FROM clause with several tables
Listing more than one table in FROM forms a Cartesian product. WHERE then filters the product. This is the same as a product followed by selection in algebra.
SELECT s.sname, c.cname
FROM Student s, Enrolled e, Course c
WHERE s.sid = e.sid AND e.cid = c.cid;The names s, e and c are tuple variables, also called aliases. They act like the rename operator ρ. Aliases are required when the same table appears twice, for example to find pairs of students of the same age.
SELECT s1.sname, s2.sname
FROM Student s1, Student s2
WHERE s1.age = s2.age AND s1.sid < s2.sid;The condition s1.sid < s2.sid removes pairs of a student with itself and also removes the mirror pair, so each pair appears once.
If you forget the join condition, the result is the full product. With n rows in Student and m rows in Course, SELECT * FROM Student, Course returns n × m rows.
Writing conditions in WHERE
WHERE accepts comparison operators (=, <>, <, <=, >, >=) combined with AND, OR and NOT. SQL also provides these shorthands.
age BETWEEN 18 AND 22is the same asage >= 18 AND age <= 22, with both ends included.sname LIKE 'A%'matches names that start with A. The symbol%matches any string of characters, and_matches exactly one character.age IN (18, 21)is the same asage = 18 OR age = 21.
Expressions and aliases in SELECT
The SELECT list can hold computed values and renamed columns.
SELECT sname AS student_name, age + 1 AS next_year_age
FROM Student;SELECT * returns all columns. In a query with several tables, it returns the columns of every table in FROM order.
Edge cases to watch
- A query over an empty table returns zero rows. A query with a WHERE condition that is never true also returns zero rows.
SELECT DISTINCT *removes only rows that are identical in every column. Two students with the same name and age but differentsidstay separate.- DISTINCT applies to the whole row of the SELECT list, not to the first column.
SELECT DISTINCT sname, ageremoves a row only if both values repeat. - Without ORDER BY, SQL gives no guarantee about row order. Do not treat the order as meaningful.
Counting rows: a worked example
Suppose Student has 4 rows with ages 18, 21, 21 and 25, and names Asha, Ravi, Ravi, Meena (the two 21-year-olds are both named Ravi but have different sids).
SELECT sname FROM Student WHERE age > 20keeps the rows with ages 21, 21 and 25. It returns 3 rows: Ravi, Ravi, Meena.SELECT DISTINCT sname FROM Student WHERE age > 20returns 2 rows: Ravi and Meena.SELECT sid FROM Student WHERE age > 20returns 3 rows. Sincesidis a key, DISTINCT would not change the count.
Summary of the correspondence
| SQL | Relational algebra | Duplicates | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| `WHERE cond` | σ_cond | Rows are kept as they are | ||||
| `SELECT a, b` | π_a,b | SQL keeps duplicates, algebra removes them | ||||
| `SELECT DISTINCT a, b` | π_a,b | Both remove duplicates | ||||
| `FROM R, S` | R × S | Product has \ | R\ | × \ | S\ | rows |
Exercise
The table Student(sid, sname, age) holds the rows (1, Asha, 20), (2, Asha, 22), (3, Ravi, 22) and (4, Ravi, 22). How many rows does each query return? (a) SELECT sname FROM Student WHERE age = 22; (b) SELECT DISTINCT sname FROM Student WHERE age = 22; (c) SELECT DISTINCT age FROM Student;
Show answer
(a) 3 rows: the rows with sid 2, 3 and 4 qualify, and the names Asha, Ravi, Ravi are all kept. (b) 2 rows: Asha and Ravi. (c) 2 rows: the distinct ages are 20 and 22.
Exercise
Student has 5 rows and Course has 4 rows. How many rows does SELECT * FROM Student, Course return if there is no WHERE clause? Does the answer change if you add DISTINCT and every row in each table is unique?
Show answer
It returns 5 × 4 = 20 rows. Adding DISTINCT does not change the count, because each combined row contains a distinct Student row and a distinct Course row, so no two product rows are identical.