SQL Execution Order
-
This follows the standard logical processing order (predefined in SQL
standards like ANSI SQL):
1. FROM/JOINs (builds initial dataset from tables).
2. WHERE (filters rows; absent here).
3. GROUP BY (groups rows, computes aggregates like SUM).
4. HAVING (filters groups using aggregates).
5. SELECT (chooses/evaluates columns, applies aliases).
6. ORDER BY (sorts final result).
7. LIMIT/OFFSET (limits rows; absent here)
What is Join?
-
A JOIN is a single optimized query handled by the DBMS, reducing
network roundtrips and leveraging indexes.
It matches rows from different tables using a common column (like CustomerID) that shares related data, as seen in Orders and Customers tables.
Advantages:
1. Reduces the need for multiple, separate queries to different tables, improving performance and lowering server load.
How join is internally implemented
-
How join is different from I doing query to table-1 storing data
and then doing query to table-2?
JOINs are implemented by the database engine (e.g., via nested loops, hash joins, or merge joins). It scans indexes or tables, matches rows on the join condition, and returns combined results.
No separate handles are opened per table; the optimizer plans a single execution path, often using memory or temp storage for efficiency.
Types of Joins
- Lets consider we have 2 tables(employee and department)
Employee-Table Departments-Table
id Name id dept
1 Alice 1 HR
2 Bob 2 IT
3 Charlie 4 Sale
| Type | Examples |
|---|---|
|
INNER JOIN Returns matching rows from both tables |
Inner join (on empid)
|
|
LEFT JOIN (or LEFT OUTER JOIN) Returns all rows from left table, matching from right; NULLs for non-matches. |
LEFT JOIN on ID=EmpID
|
|
RIGHT JOIN (or RIGHT OUTER JOIN) Returns all rows from right table, matching from left; NULLs for non-matches. |
Right JOIN on ID=EmpID
|
|
FULL OUTER JOIN Returns all rows from both tables; NULLs for non-matches. |
FULL OUTER JOIN on ID=EmpID
|
|
CROSS JOIN Cartesian product; all combinations without condition |
Returns 9 rows (3x3 combinations), e.g., Alice-HR, Alice-IT, Alice-Sales, etc. |
Complex Joins
Inner Join
| Tables | Complex SQL Query |
|---|---|
|
Order of execution
|