Quiz 2

05 - SQL Queries: SELECT, WHERE, ORDER BY

1657 words
8 min read
Python Week 1: the first filter for runtime behavior
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

📖 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):
python
results = []
for row in file:
    if row['dept_name'] == 'Comp. Sci.' and row['salary'] > 70000:
        results.append(row['name'])
SQL (declarative):
sql
SELECT 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

sql
SELECT 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

OperatorMeaningExample
=Equal todept_name = 'Comp. Sci.'
<> or !=Not equal todept_name <> 'Music'
>Greater thansalary > 70000
<Less thansalary < 50000
>=Greater than or equalsalary >= 60000
<=Less than or equalsalary <= 80000
BETWEENIn a range (inclusive)salary BETWEEN 60000 AND 80000
INIn a set of valuesdept_name IN ('CS', 'Math')
LIKEPattern matchingname LIKE 'S%'
IS NULLIs NULLgrade 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):
sql
SELECT 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:
sql
SELECT 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
PatternMatchesDoesn'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:
sql
SELECT * FROM student, department;
If student has 10 rows and department has 7, the result has 10×7=7010 \times 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.
sql
SELECT 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.
sql
SELECT name, salary
FROM instructor
WHERE dept_name = 'Comp. Sci.' AND salary >= 70000
ORDER BY salary DESC;
namesalary
Brandt92000
Katz75000

Example 3: String matching with JOIN

Query: Find names of instructors whose name contains 'in' and who teach in the Taylor building.
sql
SELECT 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:
  1. FROM: Cartesian product of instructor(I) × department(D)
  2. WHERE: Keep rows where dept_name matches, name contains 'in', building is 'Taylor'
  3. SELECT: Return unique names

📐 Key Formulas / Concepts

ClausePurposeExecution Order
SELECTChoose columns3rd
FROMSource tables1st
WHERERow filter2nd
ORDER BYSort output4th
DISTINCTRemove duplicatesAfter SELECT

⚠️ Common Pitfalls

Pitfall 1: Forgetting the WHERE Clause in Multi-Table Queries

The Mistake: Querying two tables without a join condition:
sql
SELECT 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:
sql
SELECT 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:
sql
SELECT 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:
sql
SELECT 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.

Answer
sql
SELECT 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.

Answer
sql
SELECT 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.

Answer
sql
SELECT 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 instructor returns 12 rows (some duplicate depts). SELECT DISTINCT dept_name FROM instructor returns 7 unique departments.

Q5. Write a query using AS to display instructor names and their annual salary (salary * 12).

Answer
sql
SELECT name, salary * 12 AS annual_salary
FROM instructor;

Q6. Find all instructors who work in a department whose building is either 'Watson' or 'Taylor'.

Answer
sql
SELECT 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?

Answer
NULL 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:
sql
SELECT 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.

Answer
The logical execution order is:
  1. FROM: Products of all tables (Cartesian product if multiple)
  2. WHERE: Filters rows based on condition
  3. SELECT: Picks the columns to display (or computes expressions)
  4. 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

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.