Could any body tell which query is more efficient if I want to use the new computed columns to filter, aggregate and order data? The one uses nested selection or the one duplicate the expressions in one select clause? Is it database specified?
Query1:
SELECT count(*), (age - 18) AS newcol FROM qmao_person WHERE (age - 18) > 0 GROUP BY (age - 18) ORDER BY (age - 18) DESC;
Query2:
SELECT count(*), s1.newcol FROM
(SELECT (age - 18) AS newcol FROM qmao_person) s1
WHERE s1.newcol > 0 GROUP BY s1.newcol ORDER BY s1.newcol DESC;
BTW, the question is which query will be more efficinent instead of how to optimize the query.
This query will produce identical results and beat both:
But in general, answer to your question is very vendor specific.
If vendor uses heavy optimization – like factoring out common expressions or converting subselects into joins, it is very possible that results will be identical.
That said, I would still prefer first query of yours if I could not optimize it like I just did.