2

I encountered a strange issue this morning. I was creating a view simplifying a list of applications in a Postgres table.

This failed.

CREATE OR REPLACE VIEW application_view AS 
SELECT COALESCE( nullif(full_name,''), nullif(additional_info,''), app_name) name
, id
FROM application
ORDER BY COALESCE( nullif(full_name,''), nullif(additional_info,''), app_name) 

whereas

CREATE OR REPLACE VIEW application_view AS 
SELECT COALESCE( nullif(full_name,''), nullif(additional_info,''), app_name) application
, id
FROM application
ORDER BY COALESCE( nullif(full_name,''), nullif(additional_info,''), app_name) 

worked.

I often use name as a column name in tables so any ideas as to why the first sql statement failed?

1 Answer 1

5

It's a keyword. When you want to use a keyword as an alias in the select list you have to use the word as:

select 1 name;

ERROR:  syntax error at or near "name"
LINE 1: select 1 name;

select 1 as name;

 name 
------
    1
(1 row)

From the documentation about aliases in the select list:

To specify the name to use for an output column, write AS output_name after the column's expression. (You can omit AS, but only if the desired output name does not match any PostgreSQL keyword (see Appendix C). For protection against possible future keyword additions, it is recommended that you always either write AS or double-quote the output name.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I used to think the use of 'as' was optional in all cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.