SQL Order of Operations: Avoid Logical Errors

🚀 𝗦𝗤𝗟 𝗗𝗼𝗲𝘀𝗻’𝘁 𝗥𝘂𝗻 𝗧𝗼𝗽 𝘁𝗼 𝗕𝗼𝘁𝘁𝗼𝗺 — 𝗛𝗲𝗿𝗲’𝘀 𝘁𝗵𝗲 𝗥𝗲𝗮𝗹 𝗢𝗿𝗱𝗲𝗿 Most people think SQL executes exactly how it’s written… But in reality, the database follows a completely different order. Understanding this is the key to: ✔ Writing correct queries ✔ Avoiding logical errors 💡 Remember: Always think like the SQL engine, not like the syntax. #SQL #DataAnalytics #Programming #Database #Learning #Tech #Coding #DataScience

  • diagram

The post use SQL Server syntax. So your real order is that two tables each having more than 1,000,000 rows are joined (step 1) and then filtered (step 2) for returning 87 rows. If we specified .... TOP/100 .... ORDER BY Zipcode, Lastname the solution is to read 1,000,000, sort all this rows and as the last operation (step 8) return 100 rows to the client. Or maybe the database system can solve the task more effective if we create an index containing the columns (Zipcode, Lastname). The task can be solved by reading the first 100 rows from the index. So we do not read many, many rows and sort this before returning 100 rows. We are NOT get any help from knowing your execution order, but only by knowing that SQL is declarative and have a general knowledge about SQL, Index, ... Therefor "But in reality, the database follows a completely different order." is a myth, because the database system change the order by creating an index or maybe because we have another filter value. Please tell how this statement will be executed. SELECT Zipcode, COUNT (*) FROM Person WHERE Lastname = 'Olsen' GROUP BY Zipcode HAVING Zipcode > 2000

Understanding this doesn't do anything. Remember: writing queries is an iterative process -how it optimizes your query is what is important, not the order in which it processes it. I love these posts that are a. wrong and b. don't provide anything useful to actually optimize queries

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories