Josep Ferrer Profile picture
Data Scientist & Tech Writer @KDnuggets @DataCamp @Medium | Outstand using data | Join 8k data professionals on https://t.co/VdsUvb9SKu 🧩

Dec 27, 2023, 14 tweets

Ever felt confused by SQL's execution flow? πŸ€”

Then you better stay with me!

Today let's exemplify SQL's execution order with a simple queryπŸ‘‡πŸ»

1️⃣ 𝗦𝗧𝗔π—₯π—§π—œπ—‘π—š 𝗙π—₯𝗒𝗠 𝗒𝗨π—₯ π—₯𝗔π—ͺ π—§π—”π—•π—Ÿπ—˜
We use a dummy table with the salary of employees depending on their field and experience,

🎯 Our main goal?
Understand the field that earns the most.

2️⃣ π—¦π—€π—Ÿ π—€π—¨π—˜π—₯𝗬 𝗦𝗧π—₯𝗨𝗖𝗧𝗨π—₯π—˜ (to use)
We define a query to obtain our goal data.

3️⃣ π—¦π—€π—Ÿ 𝗔𝗦 𝗔 π——π—˜π—–π—Ÿπ—”π—₯π—”π—§π—œπ—©π—˜ π—Ÿπ—”π—‘π—šπ—¨π—”π—šπ—˜
SQL expects statements to be written in a specific orderβ€Š...

but their evaluation sequence differs.

π—¦π—§π—˜π—£ 1 - 𝗙π—₯𝗒𝗠
First SQL determines the table where to take the data from.

In our case our dummy table salaries with all the info it contains.

π—¦π—§π—˜π—£ 2 - π—ͺπ—›π—˜π—₯π—˜
Here data is filtered.

This is where we specify conditions to narrow down our results.

Think of it as our detective's magnifying glass! πŸ”

π—¦π—§π—˜π—£ 3 - π—šπ—₯𝗒𝗨𝗣 𝗕𝗬
Grouping time!

This step clusters similar data together based on a specified column.

Perfect for summarizing data like employee fields! πŸ“Š

π—¦π—§π—˜π—£ 4 - π—›π—”π—©π—œπ—‘π—š
It's like WHERE's big sibling.

HAVING filters groups, especially useful after GROUP BY.

Only the groups meeting our criteria will pass this gate.

π—¦π—§π—˜π—£ 5 - π—¦π—˜π—Ÿπ—˜π—–π—§
The star of the show!

Here we pick the columns we want to see in our final output.

Like an artist choosing colors for their painting 🎨

π—¦π—§π—˜π—£ 6 - 𝗒π—₯π——π—˜π—₯ 𝗕𝗬
Now we arrange our results.

This is where we decide the sorting order, like arranging books on a shelf. πŸ“š

π—¦π—§π—˜π—£ 7 - π—Ÿπ—œπ— π—œπ—§
The final touch!

Here we can limit the number of rows in our result set.

It's like picking the top 10 hits of the year. 🌟

4️⃣ π—™π—œπ—‘π—”π—Ÿ π—₯π—˜π—¦π—¨π—Ÿπ—§
And voilΓ ....!

we have our neatly arranged and insightful data, ready for action!

Next week we will see how a JOIN command would affect this flow!

Still no clear how SQL's execution flow works?

Check my previous thread to further understand it! πŸ‘‡πŸ»

And that's all for now

If you liked this thread, I am sharing Data Science and AI content.
So don't forget to follow me to get more content like this! (@rfeers)

RT the tweet below to help me share the word! :D

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling