Add row to query result using select
Incorporate a new row into your SQL query's result with UNION ALL and a separate SELECT for defining static values. Ensure column number and types correspond:
Replace 'Fixed Value', 0, 'Another Value' with your desired values matching the number and data type of your_table columns.
Deciding Between union and union all
When debating between UNION
or UNION ALL
, bear in mind that UNION
automatically discards duplicate rows, while UNION ALL
retains every row, duplicates as well. Here's a shorthand:
- If distinct results are required and duplicate rows should be eliminated, opt for
UNION
. - Where duplicates are meaningful,
UNION ALL
preserves them. It's also quicker since it doesn't need to sift out unique records.
Combining static and dynamic data
In some cases, you may wish to append rows using data derived from other queries or tables, not just fixed values. The same technique could be utilized:
Coordinating data types
While using UNION
or UNION ALL
, make sure the data types of each column are compatible. If one column is integer and another is varchar, casting can be used to align these data types:
This ensures the data in the final result set works together flawlessly.
Compatibility with SQL Server and Oracle
In SQL Server, the equivalent of adding a row with hardcoded values would take this form:
For Oracle, there's a peculiar FROM DUAL
statement which serves the same purpose:
In Oracle, DUAL
is a special one-row, one-column table that comes preinstalled in all Oracle databases.
Was this article helpful?