ORDER BY with NULL values behavior
📖 Scenario: You work in a company database where some employees have not yet been assigned a department. You want to list all employees sorted by their department, but you want to control where the employees with no department (NULL) appear in the list.
🎯 Goal: Build a SQL query that orders employees by their department name, showing employees with NULL department either first or last using ORDER BY with NULLS FIRST and NULLS LAST.
📋 What You'll Learn
Create a table called
employees with columns id (integer), name (text), and department (text, nullable).Insert exactly these rows into
employees: (1, 'Alice', 'Sales'), (2, 'Bob', NULL), (3, 'Charlie', 'HR'), (4, 'Diana', NULL), (5, 'Eve', 'IT').Write a query to select all columns from
employees ordered by department with NULL values appearing first.Write a query to select all columns from
employees ordered by department with NULL values appearing last.💡 Why This Matters
🌍 Real World
Handling NULL values in sorting is common when working with real-world data where some information may be missing or optional.
💼 Career
Knowing how to control the position of NULLs in ordered query results is important for data analysis, reporting, and database management roles.
Progress0 / 4 steps