SQL Riddles to Test Your Wits

Author:Murphy  |  View: 23400  |  Time: 2025-03-23 19:42:18

SQL is a deceptively simple language. Across its many dialects, users can query databases in a syntax similar to English. What you see is what you get… until you don't.

Every now and then I come across a query that produces a result completely different from what I expected, teaching me little nuances about the language. I've compiled three recent head-scratchers in this post, and I've arranged them as riddles to make them more interesting. Try to figure out the answer before reading the end of each section!

I've also included quick common table expressions (CTEs) to generate the tables in each example, so you don't need to try querying your company's production tables! But to get really comfortable with SQL, I actually recommend creating your own database and tables to play with. Check out this post to learn how.

Note that all queries are in Postgres – you may get different results in a different dialect. Finally, an obligatory note that the actual data and topics in each query are just illustrative examples.

Tags: Hands On Tutorials Postgres Programming Sql Technology

Comment