← Back to SQL, page 1

sql-0015 · Easy fresher

A table has a column named order. Why does CREATE TABLE fail, and how do you fix it?

ORDER is a reserved word, so the parser reads it as the start of an ORDER BY clause and raises a syntax error. Quote it as an identifier with double quotes, or better, rename it to something like sort_order or position so nobody has to quote it again.

Full answer

SQL reserves certain words for its own grammar: SELECT, FROM, ORDER, GROUP, USER, TABLE and many more. When one appears where a name is expected, the parser gets confused:

sql
CREATE TABLE playlist (id INTEGER, order INTEGER);  -- error on purpose
text
Error: near "order": syntax error

Double quotes turn the word into an identifier and the statement works:

sql
CREATE TABLE playlist (id INTEGER, "order" INTEGER);
INSERT INTO playlist VALUES (1, 2), (2, 1);
SELECT id, "order" FROM playlist ORDER BY "order";
idorder
21
12

The catch is that every future query must quote it too, and forgetting the quotes in one place produces a confusing syntax error far from the table definition. Renaming the column is the better fix:

sql
CREATE TABLE playlist2 (id INTEGER, sort_order INTEGER);
INSERT INTO playlist2 VALUES (1, 2), (2, 1);
SELECT id, sort_order FROM playlist2 ORDER BY sort_order;
idsort_order
21
12

Reserved word lists differ between engines. user is reserved in PostgreSQL but usable as a plain column name in SQLite, so a schema that works in local SQLite tests can fail on PostgreSQL. Names like user, order, group, desc and date are common candidates for trouble.

sql
-- error on purpose
CREATE TABLE playlist (id INTEGER, order INTEGER);

CREATE TABLE playlist (id INTEGER, "order" INTEGER);
INSERT INTO playlist VALUES (1, 2), (2, 1);
SELECT id, "order" FROM playlist ORDER BY "order";

CREATE TABLE playlist2 (id INTEGER, sort_order INTEGER);
INSERT INTO playlist2 VALUES (1, 2), (2, 1);
SELECT id, sort_order FROM playlist2 ORDER BY sort_order;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Reserved words cannot be used as bare identifiers
  • Double quotes allow it, but every query then needs the quotes
  • Renaming to a descriptive non-reserved word is the lasting fix
  • Reserved word lists differ by engine

Common mistakes

  • Quoting the name in CREATE TABLE and forgetting the quotes in later queries
  • Testing only on SQLite and missing a word that PostgreSQL reserves

Follow-ups

  • Why is a table called user a problem in PostgreSQL?
  • What naming conventions help avoid reserved words?

Tips

  • Recommend the rename, not just the quoting