Drafting Queries Without a Table


Sometimes, we just want to try or demo a specific way to use SQL. Even if the query is simple, it can become a tedious task if it requires test data that is not yet available in any table. In such cases, the values statement can be handy.

In its full power, values can not only provide data to the insert statement, but be used as stand-alone statement very much like select. Unlike select, values doesn't access any tables but only the data that is explicitly listed in the SQL statement.

The following example demonstrates that COUNT(*) and COUNT(expression) mean something different0:

SELECT COUNT(c1)
     , COUNT(*)
  FROM (VALUES (1)
             , (NULL)
       ) t1(c1)

The example uses the values clause to produce a table with two rows and one column (of unknown name). One of the values is null. To be able to refer to this column, and thus be able to apply an aggregate function upon it, the example aliases this derived table as t1 and its column as c1 using the alias columns in from syntax. Alternatively, you can use a with clause to name the columns. t1 and its columns can now be used like a regular table of view.

Compatibility

The example conforms to full SQL-92 and later standards with the optional features F641, F591 and F6611.

About the Author

Photo of Markus Winand

Markus Winand teaches efficient SQL—inhouse and online. He minimizes the development time using modern SQL and optimizes the runtime with smart indexing—for that he also published the book SQL Performance Explained.

Footnotes

  1. COUNT(*) counts rows (SQL-92, §6.5, General Rule 1a; SQL:2016, Part 2, §10.9 General Rule 5).

    COUNT(expression) counts not null values (SQL-92, §6.5, General Rule 1b; SQL:2016, Part 2, §10.9 General Rule 7a).

  2. Validated at http://developer.mimer.se/validator/index.htm.

“modern SQL” by Markus Winand is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License.
Legal | Contact | NO WARRANTY | Trademarks | Privacy | CC-BY-NC-ND 3.0 license