sqlstreak

SQL error

ORDER BY position 3 is not in select list / 1st ORDER BY term out of range

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

A number in ORDER BY means a column position in the select list: ORDER BY 3 needs at least three selected columns. Sort by the column's name instead, which keeps working when the select list changes.

The exact messages

  • PostgreSQLERROR: ORDER BY position 3 is not in select list
  • SQLite1st ORDER BY term out of range - should be between 1 and 2

How to read this message

This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it. LINE gives the line it was reading when it gave up, and the ^ marks the exact spot.

ERROR:  ORDER BY position 3 is not in select list
LINE 3: ORDER BY 3;
                 ^

SQLite 3.54.1 reports the same mistake as 1st ORDER BY term out of range - should be between 1 and 2, with no line number: look for the word or column it names.

Why it happens

A column was removed from SELECT

ORDER BY 3 was right until the third column was deleted. Names don't have this problem.

A column name in single quotes

ORDER BY 'price' is a constant, not a column. PostgreSQL rejects it; SQLite sorts by the same constant for every row, which means no sorting at all.

Reproduce it, then fix it

Both queries run on a real database in your browser. Switch dialects to compare.

Broken
SELECT name, price
FROM menu_items
ORDER BY 3;
Fixed
SELECT name, price
FROM menu_items
ORDER BY price DESC, name;

Sort by names, not positions. name breaks ties between items with the same price.

The fix returns, PostgreSQL: first 6 of 11 rows

nameprice
BBQ Meteor15.5
Four Cheese Orbit14
Pepperoni Rocket13.5
Veggie Nebula13
Margherita11
Wings8.5

The fix returns, SQLite: first 6 of 11 rows

nameprice
BBQ Meteor15.5
Four Cheese Orbit14
Pepperoni Rocket13.5
Veggie Nebula13
Margherita11
Wings8.5

Experiment with it: PostgreSQL playground·SQLite playground

Other forms of this mistake

Each one was run when this page was built; the result is what the engine really does.

  • SELECT name, price FROM menu_items ORDER BY 'price';

    PostgreSQLERROR: non-integer constant in ORDER BY

    Quoted, 'price' is text, not the price column.

  • SELECT name, price FROM menu_items ORDER BY 'price';

    SQLiteRuns without an error

    SQLite accepts it and sorts by a constant: the rows come back unsorted.

Official documentation

Stop hitting this error

Practise the concept behind it in a five-minute lesson, or read the full guide: SQL ORDER BY, LIMIT and OFFSET.