Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

`user` name as alias for table does not work

So I have this simple query written in Postgres:

SELECT cp.contest_id, cp.username, user.rating FROM contest_participants cp 
  JOIN users user ON user.username = cp.username WHERE contest_id = '?';

and I keep getting this error:

ERROR:  syntax error at or near "."
LINE 1: SELECT cp.contest_id, cp.username, user.rating FROM contest_...

If I change the user table alias name, it’s working like a charm but is bothering me not to know why exactly is that. Is there a problem with the alias name or it can be something else with the entire schema structure from the database?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As far as I can tell, the query is isolated to the selection I made, right?

>Solution :

In Postgres SQL, user is a reserved keyword and cannot be used as an alias or other database object name, see the documentation here.

For an immediate fix, you may escape the alias in double quotes:

SELECT cp.contest_id, cp.username, user.rating
FROM contest_participants cp 
JOIN users "user" ON "user".username = cp.username
WHERE contest_id = '?';

Or, you could just an alias like usr, which gets across the same meaning without requiring escaping.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading