sqlcmd.net validated sql reference
intermediate sorting MySQL MariaDB SQL Server PostgreSQL SQLite

Control Where NULLs Appear in a Sort

Use `NULLS FIRST` or `NULLS LAST` to explicitly position NULL values at the top or bottom of a sorted result set.

Docker-validated Not currently validation-green

Sort scores ascending with NULLs at the end

Eve (78), Alice (85), and Carol (92) have scores and sort ascending by value. Bob and Dave have NULL scores. In MySQL and SQL Server, (score IS NULL) returns 0 for non-null rows and 1 for null rows — sorting that expression first pushes the NULLs to the bottom. In PostgreSQL and SQLite, NULLS LAST is a direct clause modifier on the ORDER BY column.

MySQL MariaDB
Engine-specific syntax
Setup
CREATE TABLE players (name VARCHAR(50), score INT);

INSERT INTO
  players
VALUES
  ('Alice', 85),
  ('Bob', NULL),
  ('Carol', 92),
  ('Dave', NULL),
  ('Eve', 78);
SQL
SELECT
  name,
  score
FROM
  players
ORDER BY
  (score IS NULL) ASC,
  score ASC;
namescore
Eve78
Alice85
Carol92
BobNULL
DaveNULL
SQL Server
Engine-specific syntax
Setup
CREATE TABLE players (name VARCHAR(50), score INT);

INSERT INTO
  players
VALUES
  ('Alice', 85),
  ('Bob', NULL),
  ('Carol', 92),
  ('Dave', NULL),
  ('Eve', 78);
SQL
SELECT
  name,
  score
FROM
  players
ORDER BY
  CASE
    WHEN score IS NULL THEN 1
    ELSE 0
  END ASC,
  score ASC;
namescore
Eve78
Alice85
Carol92
BobNULL
DaveNULL
PostgreSQL SQLite
Engine-specific syntax
Setup
CREATE TABLE players (name VARCHAR(50), score INT);

INSERT INTO
  players
VALUES
  ('Alice', 85),
  ('Bob', NULL),
  ('Carol', 92),
  ('Dave', NULL),
  ('Eve', 78);
SQL
SELECT
  name,
  score
FROM
  players
ORDER BY
  score ASC NULLS LAST;
namescore
Eve78
Alice85
Carol92
BobNULL
DaveNULL

PostgreSQL and SQLite use native NULLS LAST syntax. MySQL/MariaDB prefix with (score IS NULL) ASC — which evaluates to 0 for non-null and 1 for null, pushing nulls last. SQL Server uses an equivalent CASE expression.

Where this command helps.

  • pushing rows with missing data to the end of a report regardless of sort direction
  • ensuring NULLs sort consistently across databases in cross-engine queries

What the command is doing.

By default, NULL ordering varies by engine: PostgreSQL and SQLite treat NULLs as greater than any non-null value, so they sort last with ASC and first with DESC. MySQL, MariaDB, and SQL Server treat NULLs as less than any non-null value, so they sort first with ASC. The ANSI-standard NULLS FIRST and NULLS LAST modifiers let you override the default explicitly. PostgreSQL and SQLite support this syntax natively. MySQL, MariaDB, and SQL Server do not — use a CASE expression that maps NULL to 0 or 1 as a sort prefix instead.