Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are subqueries evil?

Tags:

sql

subquery

This question comes after a friend's comment. He said that when a query has a lot of subqueries, it's a signal that the database has design flaws and they must be avoided. He also said that many books suggest the same.

I agree in parts, but I think that are queries that have complex logic that a lot of subqueries are needed, or, to avoid the subqueries, a materialized view of a query or a lot of data redundancy.

So, what is the truth about subqueries? Must they always be avoided? No problems with them? Do they indicate database design flaws? Is it possible to have a database design that allows complex queries without having data redundancy?

like image 397
Renato Dinhani Avatar asked Dec 04 '22 19:12

Renato Dinhani


2 Answers

No, the presence of subqueries does not necessarily mean a database schema is poorly designed.

Correlated subqueries should be used sparingly (i.e. when an inner condition refers to an outer clause).

Other than that, subqueries are often a useful and a natural way of solving a problem. I tend to use joins rather than subqueries where possible.

Many query optimisers will transform certain types of subqueries into joins.

like image 184
Mitch Wheat Avatar answered Dec 08 '22 14:12

Mitch Wheat


Your friend's logic is flawed.

Although SQL and its various implementations is based, somewhat loosely, on the relational model, it lacks keywords or shorthands for many basic relation operators, notably semi join, semi difference (a.k.a. anti join) and divide. I often write semi join and semi difference in SQL code using subqueries; as for divide, I'm not sure it is possible to perform in a single query without using subqueries!

So my use of subqueries is determined by the questionable design of the SQL language, rather than the design of the database I'm using.

p.s. I wonder if you and/or your friend is using the term "database" to mean both database (the collection of data) and DBMS (the software system managing the data) interchangeably. If so and in context you mean DBMS then the statement "when a query has a lot of subqueries, it's a 'smell' that the DBMS has design flaws" may indeed be true.

like image 22
onedaywhen Avatar answered Dec 08 '22 15:12

onedaywhen