- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Data
Filter and Organize Enrollment Records with SQL in PostgreSQL
In this Code Lab, you'll practice writing SQL queries in PostgreSQL to retrieve and organize student enrollment records. You'll use SELECT, WHERE, AND, OR, and NOT to filter data, apply pattern matching with LIKE and ILIKE, handle NULL values, and structure output using ORDER BY, LIMIT, and OFFSET. You'll also create computed columns using CASE and COALESCE. By the end, you'll be able to build practical queries that mirror real-world data requests from academic administrators and IT departments.
Lab Info
Table of Contents
-
Challenge
Step 1: Filter Student Records for a Specific Term
Step 1: Filter Student Records for a Specific Term
Welcome to the lab! As a data analyst, your most fundamental task is retrieving data. In this step, you'll learn to select records from a table and filter them based on specific criteria using the
SELECT,FROM, andWHEREclauses.The
studentsTableAll of your queries will run against a pre-populated table named
students. It contains student enrollment information, including names, courses, academic terms, and enrollment status.Basic Retrieval with
SELECTandFROMThe most basic SQL query retrieves all data from a table. The asterisk (
*) is a wildcard that means "all columns."SELECT * FROM students;Filtering with the
WHEREClauseTo narrow your results, you use the
WHEREclause. It acts as a filter, telling the database to return only the rows that match a specific condition. For example, to find all students in a particular course, you would write:SELECT * FROM students WHERE course = 'CS101';Notice that text values (strings) must be enclosed in single quotes (
').Combining Filters with
ANDReal-world questions often require multiple conditions. You can combine filters using the
ANDoperator. The query will only return rows that satisfy all of the specified conditions.SELECT * FROM students WHERE term = 'Fall 2025' AND status = 'active';Now, let's apply these concepts to answer some requests from the registrar's office. You will write your queries in the
.sqlfiles located in theworkspacedirectory.How to Run SQL Files in PostgreSQL
When you need to execute a SQL script from the terminal, run:
psql -d postgres -f filename.sqlThe output may enter paging mode and you see
(END)at the bottom of the terminal, press:qto return to the normal terminal prompt.
-
Challenge
Step 2: Apply Logical Operators to Combine Filters
Step 2: Apply Logical Operators to Combine Filters
In the previous step, you used
ANDto combine filters. Now, you'll expand your toolkit withORandNOTto handle more complex logical scenarios. You'll also learn why parentheses are crucial for controlling the order of operations.The
OROperatorThe
ORoperator returns rows that match at least one of the given conditions. It's useful when you need data from multiple, alternative categories.For example, to get a list of students in either the computer science or math department:
SELECT * FROM students WHERE course = 'CS101' OR course = 'MATH202';The
NOTOperatorThe
NOToperator inverts a condition. It's often used to exclude a specific category from your results. For example, to find all students who are not inactive:SELECT * FROM students WHERE NOT status = 'inactive';This is equivalent to using the
!=or<>operator:WHERE status != 'inactive'.Controlling Logic with Parentheses
When you mix
ANDandOR, SQL follows a specific order of operations (ANDis typically evaluated beforeOR). This can lead to unexpected results. To ensure your logic is evaluated correctly, use parentheses()to group conditions.Imagine you need active students from either the 'Fall 2025' or 'Spring 2025' term. This query is incorrect:
-- Incorrect: This might return inactive students from Spring 2025 SELECT * FROM students WHERE status = 'active' AND term = 'Fall 2025' OR term = 'Spring 2025';The correct way is to group the
ORconditions:-- Correct: Groups the term conditions first SELECT * FROM students WHERE status = 'active' AND (term = 'Fall 2025' OR term = 'Spring 2025');Let's put this into practice.
-
Challenge
Step 3: Use Pattern Matching for Partial Text Search
Step 3: Use Pattern Matching for Partial Text Search
Sometimes, you don't know the exact value you're searching for, or you need to find records that follow a certain pattern. SQL's
LIKEoperator is perfect for this. It allows you to perform partial text searches using wildcards.Wildcard Characters
There are two primary wildcards:
%(Percent sign): Matches any sequence of zero or more characters._(Underscore): Matches any single character.
Using
LIKELIKEis case-sensitive in PostgreSQL. Here are some examples:- To find all courses that start with 'Intro':
SELECT course FROM students WHERE course LIKE 'Intro%'; - To find all students whose last name ends with 'son':
SELECT last_name FROM students WHERE last_name LIKE '%son'; - To find all courses that contain the word 'Data':
SELECT course FROM students WHERE course LIKE '%Data%';
Case-Insensitive Matching with
ILIKEOften, you'll want to find a pattern regardless of its capitalization. PostgreSQL provides a convenient, non-standard operator called
ILIKEfor this.- To find all courses containing 'data' (matching 'data', 'Data', etc.):
SELECT course FROM students WHERE course ILIKE '%data%';
Now it's your turn to find records based on patterns.
-
Challenge
Step 4: Handle Missing or NULL Values
Step 4: Handle Missing or NULL Values
In the real world, datasets are rarely perfect. A common issue is missing data, which is represented in SQL by the special value
NULL.NULLdoesn't equal anything—not even itself! This means you can't use standard comparison operators like=or!=to find it. In this step, you'll learn the correct way to handleNULLvalues.Filtering for
NULLwithIS NULLTo find rows where a value is missing, you must use the
IS NULLoperator.- To find all students who do not have an email address on file:
SELECT * FROM students WHERE email IS NULL;
Similarly, to find all students who do have an email, you would use
IS NOT NULL.Providing Default Values with
COALESCEWhen you're creating a report, showing a blank space or
NULLfor missing data can be confusing. TheCOALESCEfunction lets you provide a fallback value. It takes a list of arguments and returns the first one that is notNULL.- To display 'No Email Provided' for any student with a
NULLemail:SELECT first_name, last_name, COALESCE(email, 'No Email Provided') FROM students;
You can also give this new, computed column a more descriptive name using an alias with the
ASkeyword:SELECT first_name, last_name, COALESCE(email, 'No Email Provided') AS contact_info FROM students;Let's practice cleaning up our student data.
- To find all students who do not have an email address on file:
-
Challenge
Step 5: Add Conditional Logic with CASE Statements
Step 5: Add Conditional Logic with
CASEStatementsAs a data analyst, you often need to derive new information or categorize data based on existing values. SQL's
CASEstatement is a powerful tool for adding conditional,if-then-elselogic directly into your queries.Basic
CASESyntaxThe
CASEstatement goes in yourSELECTlist. It evaluates a series of conditions and returns a value when the first condition is met. It must end with anENDkeyword, and it's good practice to give it an alias withAS.CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE else_result END AS new_column_nameExample: Categorizing Courses
Let's say you want to categorize courses by their credit hours. A course with 4 credits could be a 'Major Course', while a 3-credit course is an 'Elective'.
SELECT course, credit_hours, CASE WHEN credit_hours >= 4 THEN 'Major Course' ELSE 'Elective' END AS course_type FROM students;You can include multiple
WHENclauses to handle more complex logic. TheELSEclause is optional, but without it, any rows that don't meet aWHENcondition will have aNULLvalue in the new column.Now, let's create some custom categories for our student data.
-
Challenge
Step 6: Organize Output with ORDER BY, LIMIT, and OFFSET
Step 6: Organize Output with
ORDER BY,LIMIT, andOFFSETIn this final step, you'll learn how to control the presentation of your query results. A well-organized report is much more useful than a random dump of data. You'll use
ORDER BYto sort records,LIMITto get the top results, andOFFSETto implement pagination.Sorting with
ORDER BYThe
ORDER BYclause sorts the rows in your result set. By default, it sorts in ascending order (ASC). You can specify descending order withDESC.- To sort students by last name alphabetically:
SELECT first_name, last_name FROM students ORDER BY last_name ASC; - To find the most recently enrolled students:
SELECT * FROM students ORDER BY enrollment_date DESC;
You can also sort by multiple columns. The database will sort by the first column, and then use the second column to sort any rows that had the same value in the first column.
-- Sort by term, and then by last name within each term SELECT * FROM students ORDER BY term, last_name;Pagination with
LIMITandOFFSETWhen working with thousands of records, you rarely want to see them all at once.
LIMITrestricts the number of rows returned, whileOFFSETtells the database how many rows to skip before starting to count.- To get the top 5 most recently enrolled students:
SELECT * FROM students ORDER BY enrollment_date DESC LIMIT 5; - To get the next 5 (i.e., page 2), you add an
OFFSET:-- Skip the first 5, then take the next 5 SELECT * FROM students ORDER BY enrollment_date DESC LIMIT 5 OFFSET 5;
Let's apply these clauses to create some final, polished reports.
- To sort students by last name alphabetically:
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.