SELECT, WHERE & ORDER BY — The Foundation
The four clauses every SQL query is built on — pick columns, filter rows, sort, and limit. Master these and the rest of SQL fits around them.
- SELECT
- WHERE
- ORDER BY
- LIMIT
- basics
Use this when you need to:
- Pull a list of records from a table — students, orders, products, anything
- Filter to only the rows that match a condition — active users, this month's sales, students in a specific major
- Pick which columns to return so reports stay readable
- Sort by date or value, then take the top N rows for "most recent" or "top 10" reports
Every query starts with SELECT. It picks columns from a table, optionally filtered with WHERE, sorted with ORDER BY, and capped with LIMIT. The shape is consistent across every database — once you have this, the rest of SQL is just specialized clauses that slot into the same skeleton.
SELECT — choose your columns
-- Pick specific columns SELECT first_name, last_name, preferred_email_address FROM ods_person; -- Or every column SELECT * FROM ods_person;
Avoid SELECT * in production code. Listing columns explicitly makes the query self-documenting, lets the planner skip work, and prevents downstream code from breaking when someone adds a column to the table.
WHERE — filter rows
-- One condition
SELECT first_name, last_name
FROM ods_person
WHERE residence_state = 'TX';
-- Multiple conditions with AND / OR
SELECT first_name, last_name
FROM ods_person
WHERE residence_state = 'TX'
AND first_gen_ind = 'Y';
-- A list of values
SELECT scs_student, scs_course_name, scs_final_grade
FROM ods_stu_course_sec
WHERE scs_final_grade IN ('A', 'B+', 'B');
-- A range (BETWEEN includes both ends)
SELECT applications_id, appl_hs_gpa
FROM ods_applications
WHERE appl_hs_gpa BETWEEN 3.0 AND 3.5;ORDER BY — sort the result
-- Ascending (default) SELECT first_name, last_name FROM ods_person ORDER BY last_name; -- Descending. NULLS LAST keeps the 29 applications with no -- high-school GPA at the bottom: PostgreSQL sorts NULL as the -- largest value, so plain DESC would list them first. SELECT applications_id, appl_acad_program_title, appl_hs_gpa FROM ods_applications ORDER BY appl_hs_gpa DESC NULLS LAST; -- Multiple sort keys — primary then tiebreaker SELECT applications_id, appl_date, appl_hs_gpa FROM ods_applications ORDER BY appl_hs_gpa DESC NULLS LAST, appl_date;
LIMIT — cap the result
-- Top 10 applications by high-school GPA SELECT applications_id, appl_acad_program_title, appl_hs_gpa FROM ods_applications ORDER BY appl_hs_gpa DESC NULLS LAST, applications_id LIMIT 10;
LIMIT alone is non-deterministic without ORDER BY — the database is free to return any N rows. Always pair LIMIT with an ORDER BY when "top N" or "most recent N" matters.
Practise this on real university data
Write real PostgreSQL in your browser and get it graded on the rows it returns. No signup and nothing to install for your first query.