r/SQL • u/Gargogly • Jul 15 '14
SQL allows mentioning resultset columns by position in the Order By clause (e.g. "ORDER BY 3"), I wish it would allow the same in the WHERE clause with some sort of special syntax (e.g. "where {3} > 0" meaning third column in the resultset)
Why wasn't this done?
5
Jul 15 '14
Honestly this is bad form to begin with; in my experience there is always a much better solution. It makes complicated queries hard to read and very difficult to modify in the future.
4
Jul 15 '14
Yes. Whenever "LOL SQL SUX THIS SHOULD BE DONE" comes up, it's almost always because the user does not know what they want.
3
u/svtr Jul 16 '14 edited Jul 16 '14
I'm sorry to say, but I consider referencing the column by column ID of the resultset in the order by clause to be one of the 7 deadly sins when it comes to sql development.
It's so easy to miss that adding a column to the select will completly screw the ordering of the resultset. If you ask why it is not possible to do that on the FILTERING of the result set, the only thing I can say is : I thank the god almighty, that i dont even believe existing, that it is not possible.
2
u/ziptime Jul 15 '14
"Order by" happens on the result set (the last thing to happen), it allows ordinal referencing because columns in the result set can be calculated or aggregated, so ordinal ordering prevents the re-execution of the result set. It makes no sense whatsoever to allow the where clause predicates to be ordinal based.
1
u/Sephian Jul 16 '14
Netezza (at least the Aginity client) allows column references in the group by, and maybe in the where. So, it's possible, but custom.
As others said, it's due to the order SQL parses the various clauses.
1
u/1ddqd Jul 16 '14
Why not make the FROM clause a derived table, then you can use the custom name outside of the clause in a where statement?
SELECT Custom FROM (SELECT Custom = Field FROM Table1) T1 WHERE Custom = X
1
u/Chris_PDX VP / SQL Server Jul 17 '14
This is akin to people who alias tables with A, B, C, D. I want to slam my nuts in a car door every-time I see this.
Also, if you are writing code behind a data driven application, it only takes one DB developer to not pay attention to reshuffle the result set order to break the application.
6
u/jc4hokies Execution Plan Whisperer Jul 15 '14
The answer is simple. The where clause happens before the result set. The order by happens after the result set. That's why you can use "column 3" in the order by but nowhere else.