by danso · 9y ago · 0 comments
SELECT UPPER(name) AS bigname
FROM people
WHERE bigname = 'JOE';
https://stackoverflow.com/questions/38040631/postgresql-does...Apparently this is the SQL standard, which PgSQL seems to do a better job of following than SQLite, but I'm at a loss to understand why this computation is particularly problematic for PgSQL (or any variant) to adopt? Unlike other SQL standard rules that PgSQL follows that SQLite/MySQL doesn't (such as forbidding the selection of column names that aren't being GROUPed by in a GROUP BY clause), this strictness seems to be all inconvenience.
SELECT bigname
FROM (
SELECT UPPER(name) AS bigname
FROM people
) x
WHERE bigname = 'JOE'
Add columns as necessary, it should work fine.But this method can make large queries with lots of aliasing very difficult to read and lead to deep nesting. There is an alternative in MSSQL and (via a quick search) pgsql as well to keep the crazy nesting to a minimum:
-- MSSQL
SELECT bigname
FROM people
CROSS APPLY (SELECT UPPER(name) as bigname) x
WHERE bigname = 'JOE'
-- PGSQL (not 100% sure of syntax)
SELECT bigname
FROM people
LEFT JOIN LATERAL (SELECT UPPER(name) as bigname) x on true
WHERE bigname = 'JOE'
The problem is this might have a negative impact on performance because it mucks with the query planner. I've seen everything from huge, complex, CROSS APPLYs have literally zero performance penalty to completely benign single-column renames tanking query performance 10x, so beware if you use this. from people
where name = 'Joe'
select upper(name) as bigname
1. It would mirror the other clauses (insert, update, and delete) which all begin with the table name.2. It would be easier on my head. I skip the select-clause anyway when reading SQL, then come back up to it at the end, when I know the columns' source.
3. It would show that using column aliases in the where-clause would fail (unless the database did some kind of two-pass processing).
; with cte as ( select a as A, b as B, c as C from dbo.table1 tbl1 join dbo.table2 tbl2 on tbl2.id = tbl1.id) select A, B, C from cte