Why these SQLs can’t work in PostgreSQL?
SELECT * FROM (t as a);
or
SELECT * FROM (t);
ERROR: syntax error at or near ")"
Those SQLs work well in MySQL.
Why these SQLs can’t work in PostgreSQL?
SELECT * FROM (t as a);
or
SELECT * FROM (t);
ERROR: syntax error at or near ")"
Those SQLs work well in MySQL.
2
Answers
Well, it’s invalid SQL.
If you want to give the table an alias you need to use
from t as a
.The form
from (....)
requires a valid query inside the parentheses andt as a
(or justt
) is not a valid query. Additionally: a derived table (which is what(...)
defines) requires an alias. So at least it has to befrom (...) as bla
To get all rows and all columns from a table the SQL standard provides the shortcut
table some_table
which is supported by Postgres.So the following would be valid:
Typically, table alias’ are applied where there is a join. For example:
To apply an alias to a single table:
..will do it for you, no need for parentheses.
You can confirm/test by example below if value is an integer:
..or if value is a string:
postgreSQL is strongly-typed, so the first example above will work for Int and Bool values, however if you have Date or other values, you may need to apply type casting. See this link for helpful info*: http://www.postgresqltutorial.com/postgresql-tutorial/postgresql-cast.
**Remember: For psql strings, always use single quotes for values, use double quotes for table names and column names.