GROUP BY, part 2
If you’re looking for an even quicker way to write your GROUP BY
clauses, you can use the column’s index instead of its name.
For example, in our previous query, where we used GROUP BY
to calculate the average salary for each department in the employees
table, the column department
is the first column in our SELECT
clause. As a result, instead of writing the column name “department” in our GROUP BY
clause like this:
SELECT
department,
AVG(salary) AS avg_salary
FROM employees
GROUP BY department
we can simply reference the department
column’s index in our SELECT
clause. In this case, because the department
column is the first column to be mentioned in our query, we’d use the index 1, and write the following:
SELECT
department,
AVG(salary) AS avg_salary
FROM employees
GROUP BY 1
This would give the same results as the previous query.