SQL Basics: Select, Filter and Join
Write simple queries to select columns, filter rows and join two tables, using a practice database and answer keys for an introductory database course.
Quick Reference
| Clause | Purpose | Example |
|---|---|---|
| SELECT | Choose output columns | SELECT name, grade |
| FROM | Specify source table | FROM students |
| JOIN | Combine related tables | INNER JOIN classes ON students.class_id = classes.id |
| WHERE | Filter individual rows | WHERE grade >= 90 |
| ORDER BY | Sort final results | ORDER BY grade DESC |
Core Concepts
Primary & Foreign Keys
A primary key uniquely identifies each row; a foreign key links rows cleanly to another table's primary key.
INNER vs. LEFT JOIN
INNER JOIN returns only matching rows in both tables; LEFT JOIN keeps every row from the left table with NULLs for non-matches.
GROUP BY & Aggregates
Pair COUNT(), SUM(), or AVG() with GROUP BY to summarize rows per category, and filter groups with HAVING.
NULL Comparisons
Use IS NULL or IS NOT NULL—expressions like '= NULL' always evaluate to unknown.
Self-Check Practice
1. Write a query to list titles of books published after 2015, sorted alphabetically.
Show worked answer
SELECT title FROM books WHERE year > 2015 ORDER BY title ASC;
2. Which clause filters aggregated groups: WHERE or HAVING?
Show worked answer
HAVING (WHERE filters rows before grouping).
Study Notes
- Always inspect table schemas and sample rows with LIMIT 5 before writing joins.
- Qualify column names with table aliases (s.name) whenever two joined tables share a column name.