Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does SQL clause "GROUP BY 1" mean?

People also ask

What is meant by ORDER BY 1 in SQL?

it simply means sorting the view or table by 1st column of the query's result.

What does GROUP BY 2 mean in SQL?

Consider above queries: Group by 1 means to group by the first column and group by 1,2 means to group by the first and second column and group by 1,2,3 means to group by first second and third column.

What is GROUP BY clause in SQL?

In SQL, the GROUP BY clause is used to group rows by one or more columns. For example, SELECT country, COUNT(*) AS number FROM Customers GROUP BY country; Run Code. Here, the SQL command groups the rows by the country column, and counts the number of each country (because of the COUNT() function).

What does ORDER BY 2 mean in SQL?

SELECT first_name, last_name FROM sales.customers ORDER BY 1, 2; In this example, 1 means the first_name column, and 2 means the last_name column. Using the ordinal positions of columns in the ORDER BY clause is considered a bad programming practice for a couple of reasons.


It means to group by the first column regardless of what it's called. You can do the same with ORDER BY.


SELECT account_id, open_emp_id
         ^^^^        ^^^^
          1           2

FROM account
GROUP BY 1;

In above query GROUP BY 1 refers to the first column in select statement which is account_id.

You also can specify in ORDER BY.

Note : The number in ORDER BY and GROUP BY always start with 1 not with 0.


In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.

This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.

If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).


It will group by first field in the select clause