PetarT
PetarT

Reputation: 79

Using aggregate functions (MySQL)

I heard couple of times that when we use aggregate functions it is good practice (almost must have) to use HAVING or GROUP BY in some query. Can someone explain this a bit more? As far as I get it, this would help us summ or results, but is there any big difference in performance there? Do we MUST have HAVING or GROUP BY in queries where we are searching for row with MAX function for some column?

Upvotes: 1

Views: 110

Answers (2)

Fabio
Fabio

Reputation: 23480

I think that in such situation it could be very usefull to read documentation

  • If you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.

As you see if you don't use GROUP BY will means to not use any aggregate function. So it's actually a must to do and not qn option.

Learn more here

Upvotes: 2

Lawrence Barsanti
Lawrence Barsanti

Reputation: 33222

Say you have a table

'name' | 'sex'
'jeff' | 'M'
'jen'  | 'F'
'mike' | 'M'

SELECT sex, count(*) FROM myTable GROUP BY sex

This would return

'M', 2
'F', 1

Basically, you need the GROUP BY statement because you need to tell the database how to aggregate the result set (i.e. collect similar rows).

Upvotes: 0

Related Questions