Sub topic 13
Differences between database systems
The earlier chapters used the SQL standard's spelling of UNION, INTERSECT, and EXCEPT. Real databases follow it closely for UNION and UNION ALL. They differ more on INTERSECT, EXCEPT, the ALL variants, precedence, and what the parser accepts around the operators. This chapter assumes you know the operators, NULL and duplicate handling, and the precedence rules from the earlier chapters. It shows where a query that works in one system fails or changes meaning in another.
What to check first
Most porting problems come from a small set of differences:
- Whether
INTERSECTandEXCEPTexist, and under what name. - Whether
INTERSECT ALLandEXCEPT ALLexist. - Whether
INTERSECTbinds tighter thanUNIONandEXCEPT. - Whether parentheses are allowed around individual
SELECTstatements. - How
ORDER BYand row limiting attach to the combined result. - How column types and text comparisons (collation) are resolved.
Support matrix
The table summarizes common systems. Versions matter. Check the documentation for the exact release you run.
| System | `INTERSECT` and `EXCEPT` | `ALL` for `INTERSECT` and `EXCEPT` | Precedence |
|---|---|---|---|
| PostgreSQL | Both | Yes | `INTERSECT` binds tighter. `UNION` and `EXCEPT` run left to right. |
| MySQL 8.0.31 and later | Both | Yes | `INTERSECT` binds tighter. |
| MySQL before 8.0.31 | Neither. Only `UNION` and `UNION ALL`. | No | Not applicable |
| MariaDB 10.3 and later | Both | From 10.5 | Standard precedence from 10.4 |
| SQL Server | Both | No | `INTERSECT` binds tighter. `UNION` and `EXCEPT` run left to right. |
| SQLite | Both | No | All operators equal, left to right. No parentheses around selects. |
| Oracle | `MINUS`. `EXCEPT` is also accepted from 21c. | 21c and later | Documented as equal, left to right. Use parentheses. |
The safest habit is to parenthesize every query that mixes operators. The next sections cover cases where that is not possible.
MINUS in Oracle
Oracle's original name for EXCEPT is MINUS. The behavior is the same: distinct rows from the first query that are absent from the second.
SELECT email FROM newsletter_subscribers
MINUS
SELECT email FROM unsubscribed;Newer Oracle releases also accept EXCEPT, but older installations do not. If you must support old and new Oracle, use MINUS. If you must support Oracle and other systems from one code base, the NOT EXISTS form from the earlier chapter works everywhere.
Oracle has another gotcha. It treats an empty string as NULL. A row with '' in the email column is therefore treated as a NULL row. In a set operation, an empty-string email and a NULL email count as the same value, and two of them collapse into one under UNION. In PostgreSQL, SQL Server, or MySQL, '' and NULL are different values and stay separate.
Missing ALL variants
UNION ALL is available everywhere. INTERSECT ALL and EXCEPT ALL are not available in SQL Server or SQLite, and not in Oracle before 21c. They count duplicates: if a value appears 3 times in the first result and once in the second, EXCEPT ALL returns it twice.
You can emulate them by numbering the duplicates, so that every row becomes distinct, and then using the plain operator:
SELECT email
FROM (
SELECT email, rn
FROM (
SELECT email,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY email) AS rn
FROM newsletter_subscribers
) a
EXCEPT
SELECT email, rn
FROM (
SELECT email,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY email) AS rn
FROM unsubscribed
) b
) d;Suppose an email appears 3 times in newsletter_subscribers (numbered 1, 2, 3) and once in unsubscribed (numbered 1). The EXCEPT removes (email, 1) and leaves (email, 2) and (email, 3). The outer SELECT drops the number, so the email appears twice, which is the EXCEPT ALL result. Replace EXCEPT with INTERSECT for the INTERSECT ALL equivalent. On Oracle versions without EXCEPT, use MINUS. NULL emails group into one partition, so they are counted correctly.
Precedence differences
The standard gives INTERSECT higher precedence than UNION and EXCEPT. Consider this query:
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
INTERSECT
SELECT email FROM vip_list;In PostgreSQL, SQL Server, and recent MySQL, the INTERSECT runs first. The result is all customers, plus the subscribers who are also VIPs. In SQLite, and in Oracle according to its documentation, the operators are equal and run left to right. The UNION runs first, and the result is only people from either table who are also VIPs. Same text, different rows, and no error.
The fix is to state the order you mean:
(SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers)
INTERSECT
SELECT email FROM vip_list;SQLite and parentheses
SQLite does not accept parentheses around individual SELECT statements in a compound query. The previous example fails there. Wrap the inner combination in a subquery in FROM instead:
SELECT email
FROM (
SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers
) AS combined
INTERSECT
SELECT email FROM vip_list;This form is also valid in PostgreSQL, MySQL, SQL Server, and Oracle (where you write combined without AS). It is the most portable way to control evaluation order.
Sorting and limiting
A single ORDER BY at the end sorts the whole result in every system. The differences are in what it may refer to and how you limit rows.
- Names. The result takes its column names from the first query. In Oracle and SQL Server,
ORDER BYin a compound query must use those names, their aliases, or positions. Referring to an expression or to a column from the second query fails. - Positions.
ORDER BY 1works in all of the systems above and is the most portable form, though it is less readable. - Limiting.
LIMIT nworks in PostgreSQL, MySQL, MariaDB, and SQLite.FETCH FIRST n ROWS ONLYworks in PostgreSQL, Oracle 12c and later, and Db2. SQL Server usesOFFSET 0 ROWS FETCH NEXT n ROWS ONLYafterORDER BY. SQL Server'sTOPapplies to a singleSELECT, not to the combined result. - Per-branch limits. To limit one branch, parenthesize it where the system allows, or use a subquery. In SQL Server and Oracle, a plain
ORDER BYinside one branch of a compound query is an error. Put the branch in a subquery withTOPorFETCH.
(SELECT email FROM customers ORDER BY created_at DESC LIMIT 10)
UNION ALL
(SELECT email FROM newsletter_subscribers ORDER BY subscribed_at DESC LIMIT 10)
ORDER BY email;This runs in PostgreSQL and MySQL. SQLite rejects the parentheses. SQL Server and Oracle need the FETCH syntax and subqueries.
Column types and collation
All systems require the same number of columns in each branch. They differ in how they reconcile types.
- PostgreSQL resolves a common type for each column position and raises an error if none exists. For example,
UNION types text and integer cannot be matched. A bare string literal of unknown type is treated astext. - SQL Server converts to the type with higher data type precedence. A branch with an
intand a branch with avarcharcontaining letters fails with a conversion error at runtime, possibly only when a bad row is reached. - MySQL converts types implicitly and rarely errors, which can hide mistakes. Mixed character and number columns may be compared as strings or numbers depending on context.
- Large object columns have limits. Oracle does not allow
CLOBcolumns inUNION,INTERSECT, orMINUSbecause they need comparison. SQL Server rejectstext,ntext, andimagefor the same reason.
When in doubt, cast each branch explicitly, for example CAST(id AS VARCHAR(20)). Explicit casts behave the same in every branch and across systems.
Collation changes which rows count as duplicates, because UNION, INTERSECT, and EXCEPT compare text using it. MySQL's default collations are case-insensitive, so [email protected] and [email protected] merge under UNION. PostgreSQL's default is case-sensitive, so both rows stay. SQL Server depends on the database collation. If case matters to the result, compare LOWER(email) in every branch.
NULLs are consistent
One behavior does not vary. All of these systems treat NULLs as equal to each other when removing duplicates and when matching rows in INTERSECT and EXCEPT. That is why the NOT EXISTS rewrite from the earlier chapter, which uses =, can differ from EXCEPT on NULL rows in any system. Oracle's empty-string rule is the one thing that changes which values count as NULL.
Choosing a portable style
Use these rules when one query must run on several systems:
- Use
UNIONandUNION ALLfreely. - Write
INTERSECTandEXCEPTonly when every target supports them. Otherwise useEXISTSor joins. - Avoid
ALLvariants onINTERSECTandEXCEPT, or use theROW_NUMBERemulation. - Wrap mixed operators in subqueries, not bare parentheses, so SQLite accepts them.
- Order and limit only the final result, using column names from the first query.
- Cast columns explicitly and compare normalized text when case matters.
Exercise
A query reads SELECT id FROM a UNION SELECT id FROM b INTERSECT SELECT id FROM c. It returns 120 rows in PostgreSQL and 35 rows in SQLite. Explain why, and rewrite it so both systems return the PostgreSQL result.
Show answer
PostgreSQL runs INTERSECT first, so it computes b INTERSECT c and then unions that with a. SQLite treats all operators as equal and evaluates left to right, so it computes a UNION b and then intersects the result with c. To get the PostgreSQL result in both, make the INTERSECT a subquery: SELECT id FROM a UNION SELECT id FROM (SELECT id FROM b INTERSECT SELECT id FROM c) AS bc. This form needs no parentheses around individual selects, so SQLite accepts it.
Exercise
You must run EXCEPT ALL on SQL Server, which lacks it. A value appears 4 times in the first table and 1 time in the second. How many copies should the emulation return, and what does ROW_NUMBER do in it?
Show answer
It should return 3 copies. ROW_NUMBER with PARTITION BY the value numbers the copies in each table (1 to 4 in the first, 1 in the second). That makes each (value, number) pair distinct, so plain EXCEPT removes only (value, 1) and leaves numbers 2, 3, and 4. Dropping the number in an outer SELECT returns the value 3 times.
Exercise
A query uses UNION on two tables. MySQL returns one row for [email protected] and [email protected], but PostgreSQL returns two. What causes the difference, and how do you make both systems agree?
Show answer
The default collations differ. MySQL's default collation is case-insensitive, so the two emails compare as equal and UNION removes one. PostgreSQL's default is case-sensitive, so they stay distinct. To make both agree, normalize the text in each branch, for example SELECT LOWER(email) FROM customers UNION SELECT LOWER(email) FROM newsletter_subscribers.