Posts

Showing posts with the label joins

SQL Query and performance tuning - Joins in depth

Image
  🔗 Joins vs. Subqueries: What to Use and How It Works Behind the Scenes When you're working with SQL, you'll often face this question: Should I use a JOIN or a SUBQUERY? Both get the job done. But behind the scenes, your choice can affect performance, sometimes dramatically. Let’s break down the difference , peek under the hood at how joins actually work, and help you choose the right one. 🧩 What’s the Difference? Let’s say you have two tables: customers (id, name, region_id) regions (id, region_name) 🔁 Option 1: Using a JOIN SELECT customers.name, regions.region_name FROM customers JOIN regions ON customers.region_id = regions.id; 🧠 Option 2: Using a SUBQUERY SELECT name, ( SELECT region_name FROM regions WHERE regions.id = customers.region_id) AS region_name FROM customers; ✅ Both queries return the same result. But what happens under the hood? 🛠️ How Joins Actually Work Let’s break down three core join algorithms used by SQL engi...

SQL Query and performance tuning - Joins

Image
     🔗 Joining Tables in SQL How Databases Combine Data Across Tables Behind the Scenes 🧩 Why Do We Join Tables? Relational databases are designed to normalize data —which means instead of putting all data in one giant table, related information is spread across multiple smaller tables . 🎯 Example Scenario: customers table → holds client information (name, contact, status level) status_levels table → holds details for each status (label, benefits, criteria) Rather than duplicate status details for every customer, we join the two tables using a shared column: status_level . 🧠 What Is a SQL Join? A join allows you to retrieve combined data from two or more tables by matching rows based on a shared value—commonly using primary keys and foreign keys . 💬 Declarative SQL: SELECT c.name, s.benefits FROM customers c JOIN status_levels s ON c.status_level = s.level; This query: Fetches customer names from customers Fetches status benefits ...