MySQL Aggregate functions

Let’s say I have a model called “Event” and I want to run query using things such as “COUNT()”, “SUM()” , “GROUP BY” …

What’s the preferred way of doing this? Should I use “Criteria” on the Event Model? If yes, what kind of datatype should I get back? Since the Event model doesn’t have properties such as COUNT or SUM, it won’t really match no? Also, I probably won’t select the “id” field so it may not make sense.

Or should I write raw SQL statements? If yes, how do I do that? Is there a helper class?


You need this:

What about queries on itself? Not related to any table?

What? Like SHOW STATUS etc.? I’d try to use the command builder for that.

There’s a lot of information already available in the forum.


The forum search seems unreliable but works for me on second try. As an alternative use Google with


No, I meant not related to any OTHER tables. Meaning, not using external relations.

For example SUM(*) on a date range, using only 1 table

The answer is: yes, use a CDbcriteria and specify the SQL function in the select property. For more details see the search hint in my previous answer.


Can’t you do a self-referencing relation? Haven’t tried it but I don’t see why it wouldn’t work.