πŸ”— SQL Joins & Combinations
Estimated reading: 2 minutes 29 views

β›” SQL EXCEPT & MINUS – Compare and Subtract Query Results

🧲 Introduction – What is SQL EXCEPT / MINUS?

EXCEPT and MINUS are SQL set operators used to return rows from one SELECT query that do not exist in another. Think of it as query subtraction.

  • EXCEPT is used in PostgreSQL and SQL Server
  • MINUS is used in Oracle

🎯 In this guide, you’ll learn:

  • Syntax and rules for EXCEPT / MINUS
  • How they compare to JOIN, INTERSECT, and NOT IN
  • Workarounds for unsupported databases

βœ… 1. EXCEPT Syntax (PostgreSQL / SQL Server)

SELECT column1, column2 FROM table1
EXCEPT
SELECT column1, column2 FROM table2;

βœ… Returns rows from the first query not present in the second.


βž– 2. MINUS Syntax (Oracle)

SELECT column1, column2 FROM table1
MINUS
SELECT column1, column2 FROM table2;

βœ… Oracle equivalent of EXCEPT


πŸ” 3. EXCEPT vs INTERSECT vs UNION

OperatorResult DescriptionDuplicates Removed
UNIONAll distinct rows from both queriesβœ… Yes
INTERSECTRows present in both queriesβœ… Yes
EXCEPT / MINUSRows in first, not in secondβœ… Yes

🧠 4. MySQL Workaround for EXCEPT

SELECT column1, column2
FROM table1
WHERE (column1, column2) NOT IN (
  SELECT column1, column2 FROM table2
);

βœ… MySQL does not support EXCEPT or MINUSβ€”use NOT IN or LEFT JOIN instead.


πŸ” 5. Example – Customers with No Orders

SELECT customer_id FROM customers
EXCEPT
SELECT customer_id FROM orders;

βœ… Returns customer IDs that do not appear in the orders table.


πŸ“˜ Best Practices

βœ… Recommended❌ Avoid This
Use for data difference analysisUsing with different column counts
Combine with INTERSECT for completenessExpecting MySQL to support it directly
Match column positions and typesIgnoring NULL impact on comparisons

πŸ“Œ Summary – Recap & Next Steps

EXCEPT / MINUS helps you find rows that are unique to one result set. It’s useful for anti-joins, integrity checks, and de-duplication.

πŸ” Key Takeaways:

  • EXCEPT: Subtract second query from first
  • MINUS: Same in Oracle
  • Both remove duplicates automatically
  • Not available in MySQLβ€”use JOIN or NOT IN

βš™οΈ Real-World Relevance:
Used in audit reports, data quality checks, and access control testing.

➑️ Next: Learn CASE, COALESCE, or write anti-joins with LEFT JOIN and NULL filters.


❓ FAQ – SQL EXCEPT / MINUS

❓ What does SQL EXCEPT do?

βœ… Returns rows from the first query that are not in the second.

❓ What is the difference between MINUS and EXCEPT?

βœ… Functionally the same; MINUS is Oracle-specific.

❓ Does EXCEPT remove duplicates?

βœ… Yes. Use EXCEPT ALL (if supported) to keep duplicates.

❓ How can I do EXCEPT in MySQL?

βœ… Use NOT IN, LEFT JOIN with IS NULL, or subqueries.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

β›” SQL EXCEPT / MINUS

Or Copy Link

CONTENTS
Scroll to Top