Skip to Main Content
SQL Antipatterns, Volume 1
book

SQL Antipatterns, Volume 1

by Bill Karwin
October 2022
Intermediate to advanced content levelIntermediate to advanced
380 pages
9h 35m
English
Pragmatic Bookshelf
Content preview from SQL Antipatterns, Volume 1

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.

 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 Window Function

Modern SQL products implement window functions, which you can use to filter for the first (or last) ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning SQL, 3rd Edition

Learning SQL, 3rd Edition

Alan Beaulieu
SQL Antipatterns

SQL Antipatterns

Bill Karwin
High Performance MySQL, 4th Edition

High Performance MySQL, 4th Edition

Silvia Botros, Jeremy Tinley
SQL Cookbook, 2nd Edition

SQL Cookbook, 2nd Edition

Anthony Molinaro, Robert de Graaf

Publisher Resources

ISBN: 9798888650011Errata Page