SQL Subqueries and CTEs Explained Using a Beekeeping Database
A tutorial on DEV Community uses a fictional beekeeping co-op dataset to explain how subqueries and Common Table Expressions (CTEs) work in SQL. Subqueries are nested queries wrapped in parentheses that the database resolves first, passing their result to the outer query. They can return a single scalar value, a list, or a full result set, and can be correlated — re-running for each row in the outer query. The article highlights a key pitfall: using NOT IN with a subquery that may return NULL values can silently eliminate all results, making NOT EXISTS a safer alternative. CTEs are presented as an alternate syntax for the same logic, offering improved readability for complex, multi-step queries.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in