Does anyone know of a good tutorial that explains, not with just one example of an easy query, how to create complex select queries in Drupal 7 that uses the preferred method of query writing?

I've written some complex queries in my custom module that use pretty elaborate and long, basic query syntax (a select clause, order by, where, etc.). I'd like to write them in the preferred format for Drupal 7 that I BELIEVE is supposed to look something like this:


I don't find that to be a very useful primer however. I want some actual guidelines for putting together complex statements with all the various options (if something like this exists).

And is it always better to write the queries like this?

I'd like to add a pager and this seems to be the only way to that.

I hope this question isn't too ambiguous. I'm really just looking for a tutorial on constructing these types of queries. Thanks!

closed as primarily opinion-based by kiamlaluno Apr 16 '15 at 8:36

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • I'm afraid requests for tutorials are off topic here, answers tend to just be links that inevitably go stale. The rest of your question is a good one though, i.e. when to use which. If there's a particular query you're struggling to re-create using the dynamic method that would be fine too, just pop the code in the question – Clive Apr 2 '15 at 21:26
  • FWIW having a look through the public members of SelectQuery will give you a lot of information – Clive Apr 2 '15 at 21:28

If you're creating a query that will need to be modified by a 3rd party or if your creating drupal.org project code then use things like db_select().

For all other use cases I prefer db_query() as the mental overhead is a lot lower.

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