# invalid UNION/INTERSECT/EXCEPT ORDER BY clause / 1st ORDER BY term does not match any column in the result set

Source: https://sqlstreak.com/sql/errors/invalid-union-order-by-clause · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**Short answer:** After `UNION`, `INTERSECT` or `EXCEPT`, ORDER BY sorts the combined result, so it can only name its columns (by name or position), not an expression like `LENGTH(name)`. Sort in an outer query, or add the expression as a column.

## The exact messages

- PostgreSQL: `ERROR: invalid UNION/INTERSECT/EXCEPT ORDER BY clause`
- SQLite: `1st ORDER BY term does not match any column in the result set`

## How PostgreSQL prints it

```
ERROR:  invalid UNION/INTERSECT/EXCEPT ORDER BY clause
LINE 4: ORDER BY LENGTH(name);
                 ^
DETAIL:  Only result column names can be used, not expressions or functions.
HINT:  Add the expression/function to every SELECT, or move the UNION into a FROM clause.
```

## Why it happens

### Sorting by an expression

`ORDER BY LENGTH(name)` or `ORDER BY LOWER(name)` after a UNION. The expression isn't a column of the combined result.

### Sorting by a column of one side only

A column that appears in only one of the SELECTs doesn't exist in the combined result either.

## The broken query

```sql
SELECT name FROM customers
UNION
SELECT name FROM staff
ORDER BY LENGTH(name);
```

## The fix

```sql
SELECT name FROM (
  SELECT name FROM customers
  UNION
  SELECT name FROM staff
) everyone
ORDER BY LENGTH(name), name;
```

Wrap the UNION in a subquery; the outer query may sort by any expression. The second sort key, `name`, makes ties come out in a fixed order.

| name |
| --- |
| Noah Kim |
| Zara Ali |
| Rosa Vega |
| Ben Carter |
| Ellie Park |
| Jonah Reed |

(6 of 18 rows)
