The EXCEPT clause returns only those rows that result from the first query without the second.
- Both queries must have the same number of columns in the same order and data type.
- The result of
EXCEPTcan contain duplicate rows. UseEXCEPT DISTINCTif this is not desirable. - Multiple
EXCEPTstatements are executed from left to right if parentheses are not specified. - The
EXCEPToperator has the same priority as theUNIONclause and lower priority than theINTERSECTclause.
Syntax
EXCEPT() can be used to exclude columns from a result in the same table, as is possible with BigQuery (Google Cloud), using the following syntax:
Examples
The examples in this section demonstrate usage of theEXCEPT clause.
Filtering Numbers Using the EXCEPT Clause
Here is a simple example that returns the numbers 1 to 10 that are not a part of the numbers 3 to 8:
Query
Response
Excluding Specific Columns Using EXCEPT()
EXCEPT() can be used to quickly exclude columns from a result. For instance if we want to select all columns from a table, except a few select columns as shown in the example below:
Query
Response
Using EXCEPT and INTERSECT with Cryptocurrency Data
EXCEPT and INTERSECT can often be used interchangeably with different Boolean logic, and they are both useful if you have two tables that share a common column (or columns).
For example, suppose we have a few million rows of historical cryptocurrency data that contains trade prices and volume:
Query
Response
holdings that contains a list of cryptocurrencies that we own, along with the number of coins:
Query
EXCEPT to answer a question like “Which coins do we own have never traded below $10?”:
Query
Response
Using EXCEPT DISTINCT
Notice in the previous query we had multiple Bitcoin holdings in the result. You can add DISTINCT to EXCEPT to eliminate duplicate rows from the result:
Query
Response