Link to home
Create AccountLog in
Avatar of Nathan Riley
Nathan RileyFlag for United States of America

asked on

Order by and Group by syntax?

What is the difference in the Order by and Group by syntax?
SOLUTION
Avatar of Limbeck
Limbeck

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of cfrias1369
cfrias1369

I tend to use them both together

SELECT CategoryID
FROM InterestingTable
GROUP BY CategoryID
ORDER BY CategoryID

This will give me, for example,
CategoryID
1
2
4
5
7

Without the ORDER BY, I will get the same data, just not sorted.

Without the GROUP BY, I will get all the rows- sorted- but I might get duplicates wherever more than one row shared the same CategoryID

The trick comes in when you want to include other columns.  You will need to specify WHICH of the values for that given column you will want to see for that particular CategoryID.  You will use aggregate functions such as MAX or MIN or AVERAGE, etc.

Sample tables to go with the above comment:

BookID       CategoryID     Cost      Description
10                1                   15         Book 11
20                2                   11         Book 12
30                4                   19         Book 13
40                7                   25         Book 31
50                5                   5           Book 11
60                5                   35         Book 21
70                2                   35         Book 21