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:
CREATE TABLE playlist (id INTEGER, order INTEGER); -- error on purposeError: near "order": syntax errorDouble quotes turn the word into an identifier and the statement works:
CREATE TABLE playlist (id INTEGER, "order" INTEGER);
INSERT INTO playlist VALUES (1, 2), (2, 1);
SELECT id, "order" FROM playlist ORDER BY "order";| id | order |
|---|---|
| 2 | 1 |
| 1 | 2 |
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:
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;| id | sort_order |
|---|---|
| 2 | 1 |
| 1 | 2 |
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.
-- 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