05 - SQL Queries: SELECT, WHERE, ORDER BY
1657 words
8 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# 05 - SQL Queries: SELECT, WHERE, ORDER BY ## 🎯 Learning Objectives After reading this topic, you will be able to: - Write SELECT-FROM-WHERE queries to retrieve data - Use DISTINCT, ORDER BY, and column aliases - Apply string pattern matching with LIKE - Combine conditions with AND, OR, and NOT - Write queries wit...

05 - SQL Queries: SELECT, WHERE, ORDER BY
🎯 Learning Objectives
After reading this topic, you will be able to:
- Write SELECT-FROM-WHERE queries to retrieve data
- Use DISTINCT, ORDER BY, and column aliases
- Apply string pattern matching with LIKE
- Combine conditions with AND, OR, and NOT
- Write queries with Cartesian products and join conditions
📋 Prerequisites
- 04 - SQL DDL — Understanding of tables and columns
- 03 - Relational Model — Relations, tuples, attributes
📖 Core Content
5.1 Intuition: SQL is Declarative
Unlike Python or Java (where you specify EVERY step), SQL is declarative — you say WHAT you want, not HOW to get it.
Python (procedural):
pythonresults = [] for row in file: if row['dept_name'] == 'Comp. Sci.' and row['salary'] > 70000: results.append(row['name'])
SQL (declarative):
sqlSELECT name FROM instructor WHERE dept_name = 'Comp. Sci.' AND salary > 70000;
The DBMS figures out the best way to execute it (use an index? Scan the table?).
Why This Matters: Declarative queries are easier to write, maintain, and optimize. The same SQL works on any database (PostgreSQL, MySQL, Oracle) — the system handles the implementation details.
5.2 The Basic SELECT Statement
sqlSELECT column1, column2, ... FROM table_name WHERE condition;
Execution order: FROM → WHERE → SELECT (not the written order!)
Simple Queries
sql-- All columns, all rows SELECT * FROM instructor; -- Specific columns SELECT name, salary FROM instructor; -- All Comp. Sci. instructors SELECT name FROM instructor WHERE dept_name = 'Comp. Sci.';
5.3 DISTINCT: Removing Duplicates
Unlike relational algebra (which automatically removes duplicates), SQL preserves duplicates by default.
sql-- WITH duplicates (default) SELECT dept_name FROM instructor; -- Output: Comp. Sci., Finance, Music, Physics, History, Comp. Sci., ... -- WITHOUT duplicates SELECT DISTINCT dept_name FROM instructor; -- Output: Comp. Sci., Finance, Music, Physics, History
When to use: Use DISTINCT only when you need unique values. It adds a sorting/grouping step that costs performance on large datasets.
5.4 WHERE Clause: Filtering Rows
| Operator | Meaning | Example |
|---|---|---|
= | Equal to | dept_name = 'Comp. Sci.' |
<> or != | Not equal to | dept_name <> 'Music' |
> | Greater than | salary > 70000 |
< | Less than | salary < 50000 |
>= | Greater than or equal | salary >= 60000 |
<= | Less than or equal | salary <= 80000 |
BETWEEN | In a range (inclusive) | salary BETWEEN 60000 AND 80000 |
IN | In a set of values | dept_name IN ('CS', 'Math') |
LIKE | Pattern matching | name LIKE 'S%' |
IS NULL | Is NULL | grade IS NULL |
Combining Conditions with AND, OR, NOT
sql-- AND: Both conditions must be true SELECT name FROM instructor WHERE dept_name = 'Comp. Sci.' AND salary > 70000; -- OR: Either condition can be true SELECT name FROM instructor WHERE dept_name = 'Finance' OR dept_name = 'Music'; -- NOT: Negate a condition SELECT name FROM instructor WHERE NOT dept_name = 'Music';
Operator precedence: NOT > AND > OR. Use parentheses when in doubt:
sql-- Correct: OR evaluated first SELECT name FROM instructor I, department D WHERE I.dept_name = D.dept_name AND (I.dept_name = 'Finance' OR D.building IN ('Watson', 'Taylor'));
5.5 ORDER BY: Sorting Results
sql-- Single column ascending (default) SELECT name, salary FROM instructor ORDER BY salary; -- Single column descending SELECT name, salary FROM instructor ORDER BY salary DESC; -- Multiple columns: sort by dept_name, then by salary descending within each dept SELECT name, dept_name, salary FROM instructor ORDER BY dept_name ASC, salary DESC;
Using column position (not recommended — fragile):
sqlSELECT name, dept_name, salary FROM instructor ORDER BY 3 DESC; -- Sorts by the 3rd column (salary)
5.6 Column Aliases (AS)
Renaming columns in the output for readability:
sqlSELECT name AS instructor_name, salary AS annual_salary FROM instructor; -- Also works for table aliases (very common!) SELECT I.name, D.building FROM instructor AS I, department AS D WHERE I.dept_name = D.dept_name;
5.7 String Operations: LIKE and Patterns
The
LIKE operator uses two wildcards:%matches any sequence of characters (including empty)_matches exactly one character
| Pattern | Matches | Doesn't Match |
|---|---|---|
'S%' | 'Smith', 'Srinivasan', 'S' | 'Adams', 'srinivasan' |
'%son%' | 'Thompson', 'Jackson', 'sonar' | 'Sony' |
'___-%' | 'ABC-123', 'BIO-301' | 'CS-101' (3 chars before -) |
'%_%' ESCAPE '\' | 'hello_world' | 'helloworld' |
sql-- Names starting with 'S' SELECT name FROM instructor WHERE name LIKE 'S%'; -- Names with 'son' anywhere SELECT name FROM instructor WHERE name LIKE '%son%'; -- Course IDs with exactly 3 letters before hyphen SELECT title FROM course WHERE course_id LIKE '___-%';
5.8 Cartesian Product (Cross Join)
When you list multiple tables in FROM without a join condition, you get the Cartesian product — every combination of rows:
sqlSELECT * FROM student, department;
If student has 10 rows and department has 7, the result has 10×7=70 rows.
You almost always want to filter this down:
sql-- Correct: join condition in WHERE SELECT name, budget FROM student, department WHERE student.dept_name = department.dept_name AND budget < 100000;
5.9 Worked Examples
Example 1: Basic filtering
Query: Find the names of all instructors in the Finance department.
sqlSELECT name FROM instructor WHERE dept_name = 'Finance';
| name |
|---|
| Wu |
| Singh |
Example 2: Multiple conditions with ORDER BY
Query: List all Comp. Sci. instructors with salary >= 70000, sorted by salary descending.
sqlSELECT name, salary FROM instructor WHERE dept_name = 'Comp. Sci.' AND salary >= 70000 ORDER BY salary DESC;
| name | salary |
|---|---|
| Brandt | 92000 |
| Katz | 75000 |
Example 3: String matching with JOIN
Query: Find names of instructors whose name contains 'in' and who teach in the Taylor building.
sqlSELECT DISTINCT I.name FROM instructor I, department D WHERE I.dept_name = D.dept_name AND I.name LIKE '%in%' AND D.building = 'Taylor';
Step by step:
- FROM: Cartesian product of instructor(I) × department(D)
- WHERE: Keep rows where dept_name matches, name contains 'in', building is 'Taylor'
- SELECT: Return unique names
📐 Key Formulas / Concepts
| Clause | Purpose | Execution Order |
|---|---|---|
SELECT | Choose columns | 3rd |
FROM | Source tables | 1st |
WHERE | Row filter | 2nd |
ORDER BY | Sort output | 4th |
DISTINCT | Remove duplicates | After SELECT |
⚠️ Common Pitfalls
Pitfall 1: Forgetting the WHERE Clause in Multi-Table Queries
The Mistake: Querying two tables without a join condition:
sqlSELECT name, budget FROM student, department;
Why It's Wrong: This produces a Cartesian product — every student paired with every department. With thousands of students and hundreds of departments, you get millions of meaningless rows.
Correct: Always include a join condition:
sqlSELECT name, budget FROM student, department WHERE student.dept_name = department.dept_name;
Pitfall 2: Using = with NULL
The Mistake:
WHERE grade = NULL or WHERE grade <> NULL.
Why It's Wrong: NULL represents "unknown" — it's not a value. grade = NULL always evaluates to "unknown" (neither true nor false), so no rows are returned.
Correct: Use WHERE grade IS NULL or WHERE grade IS NOT NULL.Pitfall 3: Confusing Execution Order
The Mistake: Thinking WHERE runs after SELECT, so you can filter on aliases:
sqlSELECT salary * 12 AS annual_salary FROM instructor WHERE annual_salary > 100000;
Why It's Wrong: WHERE executes before SELECT, so
annual_salary doesn't exist yet in the WHERE clause.
Correct: Use the expression in WHERE:sqlSELECT salary * 12 AS annual_salary FROM instructor WHERE salary * 12 > 100000;
📝 Practice Questions
Q1. Write a query to find the names of all instructors whose salary is between 60000 and 80000.
AnswersqlSELECT name FROM instructor WHERE salary BETWEEN 60000 AND 80000; -- BETWEEN is inclusive: >= 60000 AND <= 80000
Q2. List all course titles whose course_id has three letters followed by a hyphen.
AnswersqlSELECT title FROM course WHERE course_id LIKE '___-%'; -- Three underscores match exactly 3 characters, % matches the rest
Q3. Find the names of all instructors in the History department, sorted by name alphabetically.
AnswersqlSELECT name FROM instructor WHERE dept_name = 'History' ORDER BY name ASC;
Q4. What is the difference between using DISTINCT and omitting it?
Answer
- Without DISTINCT: All rows matching the query are returned, including duplicates
- With DISTINCT: Duplicate rows are eliminated, only unique combinations returned
Example:SELECT dept_name FROM instructorreturns 12 rows (some duplicate depts).SELECT DISTINCT dept_name FROM instructorreturns 7 unique departments.
Q5. Write a query using AS to display instructor names and their annual salary (salary * 12).
AnswersqlSELECT name, salary * 12 AS annual_salary FROM instructor;
Q6. Find all instructors who work in a department whose building is either 'Watson' or 'Taylor'.
AnswersqlSELECT DISTINCT I.name FROM instructor I, department D WHERE I.dept_name = D.dept_name AND D.building IN ('Watson', 'Taylor');
Q7. Why does SELECT name FROM instructor WHERE salary = NULL return no rows?
AnswerNULL is not a value — it's the absence of a value. Comparison with NULL always returns "unknown" (neither true nor false). The WHERE clause only keeps rows where the condition is true.To check for NULL, use:sqlSELECT name FROM instructor WHERE salary IS NULL; SELECT name FROM instructor WHERE salary IS NOT NULL;
Q8. Explain the execution order of a SELECT-FROM-WHERE-ORDER BY query.
AnswerThe logical execution order is:
- FROM: Products of all tables (Cartesian product if multiple)
- WHERE: Filters rows based on condition
- SELECT: Picks the columns to display (or computes expressions)
- ORDER BY: Sorts the result
Note: This is the logical order. The actual execution may differ (the optimizer chooses the most efficient path).
🔗 Cross-References
- Next Topic: 06 - SQL Aggregation & Grouping
- Previous Topic: 04 - SQL DDL
- Related: BSMS2001 (BDM) — Business querying
- Related: BSCS2003 (MAD 1) — Using SQL in web applications
- Textbook: Silberschatz, Korth, Sudarshan — Chapter 3 (SQL) Join Discord Previous04 - SQL DDLNext06 - SQL Aggregation