Queries, joins, and groups

PostgreSQL 19.0

Use the students, courses, and enrollments tables from Setup. Run each query independently to see how it changes the result.

On this page

Filter rows with WHERE

WHERE keeps rows that meet the condition. This example selects courses with a fee of 25.00 or more. In the sample data, SQL Basics and Web Development match.

SELECT title, fee
FROM courses
WHERE fee >= 25.00
ORDER BY id;

Sort rows with ORDER BY

DESC shows the highest fee first. For equal fees, id ASC puts the lower ID first.

SELECT title, fee
FROM courses
ORDER BY fee DESC, id ASC;

Return the first row with LIMIT

LIMIT 1 returns at most one row. ORDER BY makes the first row predictable. SQL Basics comes first in this sample.

SELECT title, fee
FROM courses
ORDER BY fee DESC, id ASC
LIMIT 1;

Count enrollments with GROUP BY

Filtering and ordering help us find individual rows. To answer how many students are enrolled in each course, we have to combine rows by course first. GROUP BY makes one group for each course ID present in enrollments. COUNT(*) counts the enrolled students in each group.

SELECT course_id, COUNT(*) AS student_count
FROM enrollments
GROUP BY course_id
ORDER BY course_id;

Filter grouped results with HAVING

HAVING checks each group’s count after grouping. This query keeps courses with at least two students. WHERE is applied before groups are formed.

SELECT course_id, COUNT(*) AS student_count
FROM enrollments
GROUP BY course_id
HAVING COUNT(*) >= 2
ORDER BY course_id;

Keep courses with zero enrollments

Counting enrollments by course ID tells us the total for each ID that appears in the enrollment table. To include course names and courses with zero enrollments, start from the course table. LEFT JOIN keeps every course. COUNT(e.student_id) counts matching students and skips the NULLs from an unmatched course. Computer Fundamentals therefore shows 0. An INNER JOIN would return courses with a matching enrollment.

SELECT c.title, COUNT(e.student_id) AS student_count
FROM courses AS c
LEFT JOIN enrollments AS e ON e.course_id = c.id
GROUP BY c.id, c.title
ORDER BY student_count DESC, c.id;

Official references