简体   繁体   中英

SQL Query Time Complexity - Join vs Sub Query

My question is regarding dilemma when using join and sub-query methods give the same results,

Which one is better and faster? ( purely in terms of time complexity )

Does join take O(M+N) time complexity? and does sub-query take O(M*N) ?

Am I wrong to think this way? If yes, pls correct me.

Here, (M, N) are number of rows in both tables combining which the results are obtained.

I am looking for answers based on SQL standard not just MySQL.

PS - I have gone through this question and all the answers to it. It is not essentially concerned about Time Complexity part.

Does join take O(M+N) time complexity? and does sub-querytake O(M*N)? Am I wrong to think this way?

Yes, with respect, you are wrong to think this way. SQL is declarative. You use it to state the result you want, and the server figures out the best way to deliver that result -- to satisfy your query -- based on available indexes and data structures.

Thousands of years -- really! -- of developer effort have gone into figuring out all sorts of algorithms, optimizations, and hacks to reduce the complexity of the processes the servers use to satisfy queries.

As the thousands of years of experience accumulate the performance distinction between correlated subqueries and join queries gets less important.

Your thinking is wrong for a specific reason: you are thinking procedurally, not declaratively. When you assert that a particular type of query can be satisfied in, for example, O(m*n) time, you are making assumptions about procedures used to satisfy it. Generations of developers have been dedicated to making your assumptions wrong.

Certainly it's possible to create tables, indexes, and queries with pathological performance characteristics. It happens all the time. But somebody fixes an index and the problem is solved.

As far as my understanding The performance should be the same. It is much more important to have the correct indexes and clustering applied on your tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM