I've recently learned that SQL_CALC_FOUND_ROWS can give the number of rows in a table from almost any SELECT statement. It's raw SQL syntax is SELECT SQL_CALC_FOUND_ROWS field1, field2, ... FROM ...

Is there an existing way I can that inject that syntax into db_select()?

I want to use this for creating a pager, so I'm already selecting some rows in the first place. It would be handy to get a count out of the query I'm already running. Doing a separate count query would be extra work in my case.

  • Are you sure your code need to use db_select()? In most of the cases you can use db_query() which is even faster.
    – apaderno
    Mar 24, 2017 at 15:49
  • @kiamlaluno Oh sheesh, of course I could. If you put that as an answer, I will accept it : )
    – user1359
    Mar 24, 2017 at 17:59

1 Answer 1


As made evident in Compare db_query() and db_select() performance, db_query() is faster than db_select(), which should then be used when you need to make the query you are executing alterable from other module via hook_query_alter(), for example when you need to get a list of nodes for which a user has access.

If that is not your case, then you can use db_query() and using the query you are showing is quite straight as db_query("SELECT SQL_CALC_FOUND_ROWS field1, field2 FROM ...").

  • 1
    Plus there isn't any support for SQL_CALC_FOUND_ROWS in the default SelectQuery class so it would need some work and perhaps even an awkward workaround to get it working with db_select
    – Clive
    Mar 24, 2017 at 19:47
  • Right, I would rather not implement a new class just to be able to add SQL_CALC_FOUND_ROWS before the list of fields to query. But the bigger problem would probably be how to make Drupal use it without me explicitly using my class.
    – apaderno
    Mar 24, 2017 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.