SQL

NULLS FIRST / NULLS LAST

admin by @admin ADMIN
Jun 14, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Control where NULLs land in an `ORDER BY`. PostgreSQL/Oracle default NULLs to LAST in ASC, FIRST in DESC; MySQL/SQL Server flip it. Be explicit if it matters.
SQL
Raw
-- Sort ascending, putting NULLs at the bottom
SELECT name, deleted_at
FROM   users
ORDER  BY deleted_at ASC NULLS LAST;

-- Most-recently-updated first; "never updated" at the end
SELECT id, title, updated_at
FROM   posts
ORDER  BY updated_at DESC NULLS LAST;

-- MySQL doesn't support NULLS FIRST/LAST directly — emulate:
SELECT * FROM posts ORDER BY (updated_at IS NULL), updated_at DESC;
--                          ↑ 0 first (non-null), then 1 (null)

-- Use in window functions too
SELECT id, score,
       RANK() OVER (ORDER BY score DESC NULLS LAST) AS rank
FROM   players;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.