Allow select query without a table

Created on 19 April 2019, over 5 years ago
Updated 11 February 2023, almost 2 years ago

Situation

A comment on line 830 of core/lib/Drupal/Core/Database/Query/Select.php says:

// FROM - We presume all queries have a FROM, as any query that doesn't won't need the query builder anyway.

This sounds sensible, but there is in fact a use case for a query without a table. If you want to add an arbitrary result row to a db query, you can do so with a union. The raw query would look something like this (source):

SELECT age, name
FROM users
UNION
SELECT 25 AS age, 'Betty' AS name

As you can see, the second select does not specify a table, and this is valid SQL.

Problem

Currently you can try to build such a query with Drupal's Select::union like this:

$query = $this->select('my_table', 't')
  ->fields('t', [
    'id',
    'title',
  ]);
$extra_row = $this->select('');
$extra_row->addExpression(1000, 'id');
$extra_row->addExpression("'foo'", 'title');
$query->union($extra_row, 'ALL');

However, you would end up with an invalid query because it is assumed that there is always a table:

SELECT age, name
FROM {users}
UNION
SELECT 25 AS age, 'Betty' AS name
FROM {}

Proposed solution

Allow select queries without a table: When no table name is provided, do not print FROM {}.

Feature request
Status

Postponed: needs info

Version

10.1

Component
Database 

Last updated 2 days ago

  • Maintained by
  • 🇳🇱Netherlands @daffie
Created by

🇳🇱Netherlands marcvangend Amsterdam

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇺🇸United States smustgrave

    Triggering D10 tests.

  • Status changed to Postponed: needs info almost 2 years ago
  • 🇳🇱Netherlands daffie

    This sounds sensible, but there is in fact a use case for a query without a table. If you want to add an arbitrary result row to a db query, you can do so with a union.

    I have asked for a use case for this functionality and to me it is still a bit, how shall I call it, "artificial". Can you show me an actual contrib/custom module were this functionality is needed and there are no good other solutions? Postponing the issue on this.

Production build 0.71.5 2024