SQL.How are NULL values ordered by ORDER BY, how do defaults differ between databases, and how can you control their placement?

`ORDER BY` places NULL values first or last depending on the database and sort direction.

| Database | ASC default | DESC default |
|---|---|---|
| PostgreSQL, Oracle | NULLs last | NULLs first |
| MySQL, SQL Server | NULLs first | NULLs last |

In PostgreSQL and Oracle, control placement explicitly:

```sql
ORDER BY salary ASC NULLS LAST
ORDER BY salary DESC NULLS FIRST
```

A portable alternative, including MySQL and SQL Server:

```sql
ORDER BY
    CASE WHEN salary IS NULL THEN 1 ELSE 0 END,
    salary ASC;
-- Non-NULL salaries ascending, then NULLs
```

To put NULLs first, use `THEN 0 ELSE 1`.

**Interview answer:** “Default NULL ordering differs between databases. Use NULLS FIRST or NULLS LAST where supported, or a CASE expression to control placement explicitly.”
This entry was posted in Без рубрики. Bookmark the permalink.