patternsqlMinor
When is the AS keyword required?
Viewed 0 times
keywordtherequiredwhen
Problem
In the following statement (PostgreSQL 11):
I get an error. Adding parenthesis around the field expression doesn't help (
I realize that
From a language perspective, why is the
Are there any other cases when the
=> SELECT c cost FROM tt;
ERROR: syntax error at or near "cost"
LINE 1: SELECT c cost FROM tt;I get an error. Adding parenthesis around the field expression doesn't help (
SELECT (c) cost FROM tt;). But adding the AS keyword fixes it.=> SELECT c AS cost FROM tt;
cost
------
1
...I realize that
cost is a keyword, but my impression is that the AS keyword is optional. From a language perspective, why is the
AS keyword required (or helpful) here? Is the PostgreSQL behavior here standard or documented somewhere?Are there any other cases when the
AS keyword is required?Solution
From the documentation:
In the SQL standard, the optional key word AS can be omitted before an
output column name whenever the new column name is a valid column name
(that is, not the same as any reserved keyword). PostgreSQL is
slightly more restrictive: AS is required if the new column name
matches any keyword at all, reserved or not
Also:
Recommended practice is to use AS or double-quote output column names,
to prevent any possible conflict against future keyword additions.
... but my preference is to not quote & instead be consistent with using
In the SQL standard, the optional key word AS can be omitted before an
output column name whenever the new column name is a valid column name
(that is, not the same as any reserved keyword). PostgreSQL is
slightly more restrictive: AS is required if the new column name
matches any keyword at all, reserved or not
cost is a keyword, so as is required.Also:
Recommended practice is to use AS or double-quote output column names,
to prevent any possible conflict against future keyword additions.
... but my preference is to not quote & instead be consistent with using
as.Context
StackExchange Database Administrators Q#238143, answer score: 5
Revisions (0)
No revisions yet.