Just curious about SQL syntax. So if I have
SELECT
itemName as ItemName,
substring(itemName, 1,1) as FirstLetter,
Count(itemName)
FROM table1
GROUP BY it
Some DBMSs will let you use an alias instead of having to repeat the entire expression.
Teradata is one such example.
I avoid ordinal position notation as recommended by Bill for reasons documented in this SO question.
The easy and robust alternative is to always repeat the expression in the GROUP BY clause.
DRY does NOT apply to SQL.
SQL is implemented as if a query was executed in the following order:
For most relational database systems, this order explains which names (columns or aliases) are valid because they must have been introduced in a previous step.
So in Oracle and SQL Server, you cannot use a term in the GROUP BY clause that you define in the SELECT clause because the GROUP BY is executed before the SELECT clause.
There are exceptions though: MySQL and Postgres seem to have additional smartness that allows it.
SQL Server doesn't allow you to reference the alias in the GROUP BY clause because of the logical order of processing. The GROUP BY clause is processed before the SELECT clause, so the alias is not known when the GROUP BY clause is evaluated. This also explains why you can use the alias in the ORDER BY clause.
Here is one source for information on the SQL Server logical processing phases.
Beware of using aliases when grouping the results from a view in SQLite. You will get unexpected results if the alias name is the same as the column name of any underlying tables (to the views.)
In at least Postgres, you can use the alias name in the group by clause:
SELECT itemName as ItemName1, substring(itemName, 1,1) as FirstLetter, Count(itemName) FROM table1 GROUP BY ItemName1, FirstLetter;
I wouldn't recommend renaming an alias as a change in capitalization, that causes confusion.
I'm not answering why it is so, but only wanted to show a way around that limitation in SQL Server by using CROSS APPLY
to create the alias. You then use it in the GROUP BY
clause, like so:
SELECT
itemName as ItemName,
FirstLetter,
Count(itemName)
FROM table1
CROSS APPLY (SELECT substring(itemName, 1,1) as FirstLetter) Alias
GROUP BY itemName, FirstLetter