MySQLism: Use SELECT(DISTINCT ) only for one field, use SELECT COUNT(*) FROM (SELECT DISTINCT ... ) ... for multiple
Last updated on
18 January 2018
Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites
SQL99 specifies COUNT(DISTINCT ) as only taking a single parameter. MySQL and DB/2 support a list of fields for this function, Postgres will support it from version 9.0 and MSSQL and Oracle do not support it in any current versions.
SELECT COUNT(DISTINCT the_field) FROM the_table
is fine on any database engine.
SELECT COUNT(DISTINCT first_field, second_field, third_field) FROM the_table
will only work on MySQL or DB/2 and should rather be written as
SELECT COUNT(*) FROM (SELECT DISTINCT first_field, second_field, third_field FROM the_table) AS distinct_three
to work more generally.
using DBTNG in Drupal 7 this would look like
db_select($table)
->fields($table, array('field1', 'field2'))
->distinct()
->countQuery();
Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.