Ira SQL ProIra SQL Pro

NULLS FIRST / NULLS LAST

intermediatefiltering
2 min read

What are NULLS FIRST and NULLS LAST?

By default PostgreSQL places NULLs last when sorting in ascending order and first when sorting in descending order. The NULLS FIRST and NULLS LAST modifiers let you explicitly control this behavior.

Syntax

SELECT * FROM table_name
ORDER BY column ASC NULLS FIRST;
SELECT * FROM table_name
ORDER BY column DESC NULLS LAST;

When to Use

  • When you want NULLs to appear at the top or bottom regardless of sort direction
  • Reports where missing data should be clearly visible at the end
  • Sorting optional fields where NULL means "not yet assigned"

Key Points

  1. Default Behavior — ASC puts NULLs last; DESC puts NULLs first.
  2. Override — NULLS FIRST forces NULLs to the top; NULLS LAST forces them to the bottom.
  3. Per Column — You can set it independently for each ORDER BY column.
  4. Index Support — B-tree indexes can be created with NULLS FIRST/LAST for matching sort order.
  5. Standard SQL — This syntax is part of the SQL standard.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

NULLS FIRST / NULLS LAST Challenge

Write a query that solve this task: show students sorted by grade, NULLs at the top.

Expected result

Students with NULL grade appear first, followed by grades in ascending order.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What are NULLS FIRST and NULLS LAST?

Initializing database...Each run starts from fresh sample data.

More Examples

NULLs last in descending order

Show products by price descending with NULLs at the bottom.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

What is the default NULL position in ORDER BY?
In PostgreSQL, NULLs sort last in ASC order and first in DESC order.
Can I use NULLS FIRST with multiple ORDER BY columns?
Yes. Each column in ORDER BY can have its own NULLS FIRST or NULLS LAST modifier.

Related Topics