sqlcmd.net validated sql reference
beginner conditional-logic MySQL MariaDB SQL Server PostgreSQL SQLite

Replace NULL Values With COALESCE

Return the first non-null value from a list of expressions.

Docker-validated Not currently validation-green

Display a fallback value when nickname is null

If nickname is null, the expression falls back to the literal 'anonymous'.

Rows loaded before the example query runs.
Setup
CREATE TABLE members (id INT, nickname VARCHAR(50));

INSERT INTO
  members (id, nickname)
VALUES
  (1, 'ace'),
  (2, NULL);
Shared across supported engines.
SQL
SELECT
  id,
  COALESCE(nickname, 'anonymous') AS display_name
FROM
  members
ORDER BY
  id;
Returned rows for the shared example.
iddisplay_name
1ace
2anonymous

`COALESCE` behaves consistently across the supported engines in this example.

Where this command helps.

  • showing fallback display text instead of null
  • replacing missing values before exporting or reporting data

What the command is doing.

COALESCE is a portable SQL function for defaulting nulls to a fallback value. It is especially useful in result sets where missing values should display as a label, number, or alternate column instead of NULL.