Sub topic 2
Making two queries compatible
This chapter assumes you can write SELECT queries with WHERE, know what tables, rows, and columns are, and understand NULL. It covers the rules two queries must meet before UNION, INTERSECT, or EXCEPT will accept them. These rules apply to all three operators, so they are worth learning once and carefully.
The rule: same shape, matching types
A set operator stacks the rows of one query on top of the rows of another. For that to make sense, both queries must produce rows of the same shape. The SQL standard calls this being union compatible, and it comes down to three requirements:
- Both queries return the same number of columns.
- Columns in the same position have compatible data types.
- Column names do not need to match. Position decides which columns line up.
The database never matches columns by name. The first column of the first query is paired with the first column of the second query, the second with the second, and so on.
Matching the column count
If the counts differ, the database rejects the query before it reads any data. This is the most common compatibility error.
SELECT email, name FROM customers
UNION
SELECT email FROM newsletter_subscribers;This fails. PostgreSQL reports each UNION query must have the same number of columns. Other databases use different wording, but the cause is the same.
There are two ways to fix it. You can drop the extra column, or you can add a placeholder to the shorter query. The placeholder is usually a literal value, and it can double as a label for where each row came from:
SELECT email, 'customer' AS source FROM customers
UNION ALL
SELECT email, 'subscriber' AS source FROM newsletter_subscribers;Each query now returns two columns. The second column is a constant in each query, and it records the origin of every row. This label trick also keeps rows from different sources from collapsing into one under UNION, because the rows differ in the label column. Use it deliberately.
Matching the column types
Types in the same position must be compatible, which does not always mean identical. Databases apply conversion rules to find a common type for each pair of columns. The details vary by system, but the general pattern is:
| Pair of types | Usually allowed? | Typical result type |
|---|---|---|
| INTEGER and BIGINT | Yes | BIGINT |
| INTEGER and NUMERIC(10,2) | Yes | NUMERIC |
| VARCHAR(20) and VARCHAR(50) | Yes | VARCHAR(50) |
| CHAR and VARCHAR | Yes | Depends on the database |
| DATE and TIMESTAMP | Usually | TIMESTAMP |
| INTEGER and VARCHAR | Depends | Error, or implicit conversion |
| DATE and INTEGER | No | Error |
The row that causes trouble is INTEGER and VARCHAR. Strict databases such as PostgreSQL refuse it:
SELECT id FROM customers
UNION
SELECT postal_code FROM addresses;If id is an integer and postal_code is text, PostgreSQL raises an error saying the types cannot be matched. MySQL and SQL Server may instead convert one side silently. A silent conversion is more dangerous than an error, because it can change values or fail only when a particular row is reached. SQL Server, for example, converts by data type precedence, so a text column may be forced to a number and fail on the first value that is not numeric.
The reliable approach is to convert explicitly with CAST, so the result does not depend on a database's implicit rules:
SELECT CAST(id AS VARCHAR(20)) AS code FROM customers
UNION
SELECT postal_code FROM addresses;Both sides are now text. Cast toward the type that cannot lose information. Turning a number into text is safe. Turning text into a number can fail or drop leading zeros in values such as 02134.
Where the output column names come from
The result takes its column names from the first query. Aliases in the second query are ignored.
SELECT email AS contact FROM customers
UNION ALL
SELECT email AS ignored_name FROM newsletter_subscribers;The result has one column called contact. The alias ignored_name has no effect. Because of this, put your aliases in the first query and keep the second query's column list in the same order. This also matters for ORDER BY, which a later chapter covers: in many databases it can refer only to the names or positions of the first query.
Literals and NULL as placeholders
Sometimes the two sources do not have the same columns, and you want to combine them anyway. Fill the gaps with a constant. For a missing text value, use an empty string or a label. For a missing value of any type, use NULL.
SELECT email, phone FROM customers
UNION ALL
SELECT email, NULL FROM newsletter_subscribers;A bare NULL has no type of its own. Most databases accept it here and take the type from the other branch. Some do not. PostgreSQL resolves an untyped NULL in a UNION against the other side, but when every branch uses a bare NULL in that column, the type becomes text. Some other systems raise an error. If your database complains, give the NULL a type:
SELECT email, phone FROM customers
UNION ALL
SELECT email, CAST(NULL AS VARCHAR(20)) FROM newsletter_subscribers;Each query keeps its own clauses
Each branch is a full query. It can have its own FROM, JOIN, WHERE, GROUP BY, and HAVING. Compatibility only concerns the final column list of each branch.
SELECT c.email, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.total > 100
UNION ALL
SELECT s.email, 0
FROM newsletter_subscribers s
WHERE s.confirmed = TRUE;The first branch joins two tables and the second reads one, and that is fine. Both return an email and a number. The literal 0 is an integer, and o.total is numeric, so they share a common numeric type.
One restriction applies: a branch cannot carry its own ORDER BY unless it is wrapped in parentheses, and even then some databases ignore or reject it. The chapter on sorting and limiting covers this.
A worked example
Suppose you have two tables with different column names and types:
CREATE TABLE customers (
id INTEGER,
email VARCHAR(100),
signup_date DATE
);
CREATE TABLE newsletter_subscribers (
subscriber_email VARCHAR(255),
subscribed_at TIMESTAMP
);
INSERT INTO customers VALUES (1, '[email protected]', '2025-01-10');
INSERT INTO customers VALUES (2, '[email protected]', '2025-02-03');
INSERT INTO newsletter_subscribers VALUES ('[email protected]', '2025-03-01 09:30:00');
INSERT INTO newsletter_subscribers VALUES ('[email protected]', '2025-03-05 14:00:00');You want one list of email addresses with the date each person joined, from either source. The tables have different column names. The email columns differ in length, and the date columns differ in type. A query that makes them compatible looks like this:
SELECT email AS contact_email,
CAST(signup_date AS TIMESTAMP) AS joined_at,
'customer' AS source
FROM customers
UNION ALL
SELECT subscriber_email,
subscribed_at,
'subscriber'
FROM newsletter_subscribers;Walk through the checks:
- Column count: each branch returns three columns.
- Column 1:
VARCHAR(100)andVARCHAR(255)combine to a text type that can hold 255 characters. - Column 2: the first branch casts
DATEtoTIMESTAMP, so both sides are timestamps. The cast is optional in most databases, but it states your intent. - Column 3: both literals are text.
- Names come from the first branch:
contact_email,joined_at,source.
The result has four rows, one for each input row. [email protected] appears twice, once per source, because the source column differs and UNION ALL does not remove rows.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about differing column counts | One branch selects more or fewer columns | Add a placeholder or remove the extra column |
| Error about incompatible types | Number against text, or date against number | Use `CAST` in one or both branches |
| Values in the wrong columns, with no error | Columns listed in a different order in each branch | Align the select lists by position |
| Unexpected column names | Names come from the first query | Alias in the first query |
| Error about an untyped NULL | The database cannot infer a type for a bare NULL | Use `CAST(NULL AS type)` |
| Truncated or padded text | Mixed CHAR and VARCHAR, or different lengths | Cast both sides to the same type |
The third row is the most damaging, because nothing fails. If one branch lists email, phone and the other lists phone, email, and both columns are text, the database happily puts phone numbers in the email column. Always read both select lists side by side and check them against each other, one position at a time.
Exercises
Exercise
A query unions SELECT id, name FROM a with SELECT name, id FROM b. The columns id is INTEGER and name is VARCHAR. What happens in PostgreSQL, and what is the fix?
Show answer
PostgreSQL raises a type error, because position 1 pairs an integer with text. Other databases might convert silently and return mixed-up data. The fix is to list the columns in the same order in both branches: SELECT id, name FROM b.
Exercise
You union SELECT email AS contact FROM customers with SELECT email AS address FROM newsletter_subscribers. What is the name of the result column, and why?
Show answer
The name is contact. The result takes its column names from the first query, so the alias address in the second query is ignored.
Exercise
One table has (email, phone) and another has only (email). Write a UNION ALL that combines them into two columns, and say why the cast on NULL may be needed.
Show answer
SELECT email, phone FROM t1 UNION ALL SELECT email, CAST(NULL AS VARCHAR(20)) FROM t2; A bare NULL has no data type. Some databases cannot work out the common type for that column unless the NULL is given one.