On this page
Unions
Last updated on
14 October 2016
Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites
Unions
To combine the results from multiple SELECT queries into a single result you use UNION like this:
$table2 = db_select('table2', 't2')
->fields('t2', array('column3', 'column4'));
$query = db_select('table1', 't1')
->fields('t1', array('column1', 'column2'))
->union($table2);
To order the combined result the individual SELECT queries must be parenthesized which currently is not supported (see #1145076: UNION queries don't support ORDER BY clauses). A workaround is to put the UNIONed queries into a subquery and applying the ORDER BY clause to the combined result:
$table1 = db_select('table1', 't1')
->fields('t1', array('column1', 'column2'));
$table2 = db_select('table2', 't2')
->fields('t2', array('column3', 'column4'));
$query = Database::getConnection()
->select($table1->union($table2))
->fields(NULL, array('column1', 'column2'))
->orderBy('column1')
->orderBy('column2');
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.