DISTINCT & JOIN Usage

August 15, 2017 ยท View on GitHub

Consider using a sub-query with EXISTS instead of DISTINCT:

The DISTINCT keyword removes duplicates after sorting the tuples. Instead, consider using a sub query with the EXISTS keyword, you can avoid having to return an entire table.

Example

SELECT DISTINCT c.country_id, c.country_name FROM SH.countries c,
SH.customers e WHERE e.country_id = c.country_id

can be rewritten to:

SELECT c.country_id, c.country_name FROM SH.countries c WHERE  EXISTS
(SELECT 'X' FROM  SH.customers e WHERE e.country_id = c.country_id)