Solution: Use Columns Unambiguously

The sections that follow describe several ways you can resolve this antipattern and write unambiguous queries.

Query Only Functionally Dependent Columns

The most straightforward solution is to eliminate ambiguous columns from the query.

Groups/anti/groupbyproduct.sql
 
SELECT​ product_id, MAX(date_reported) ​AS​ latest
 
FROM​ Bugs ​JOIN​ BugsProducts ​USING​ (bug_id)
 
GROUP​ ​BY​ product_id;

The query reveals the date of the latest bug per product, even though it doesn’t report the bug_id corresponding to that latest bug. Sometimes this is enough, so don’t overlook a simple solution.

Using a Correlated Subquery

A correlated subquery contains a reference to the outer query and so produces different results ...

Get SQL Antipatterns now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.