What is a JOIN? Explain INNER JOIN and LEFT JOIN.
IntermediateConceptMySQL
Answer
Short answer
A JOIN combines rows from two tables using a related column. INNER JOIN returns only rows that match in both tables. LEFT JOIN returns all rows from the left table, plus matching rows from the right table (or NULL if there's no match).
Data
customers: (1, Asha), (2, Ravi), (3, Meera)
orders: (7, customer 1, 52000), (8, customer 2, 1499)
INNER JOIN — customers who have orders
SELECT c.name, o.total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id;
-- Asha | 52000
-- Ravi | 1499
LEFT JOIN — every customer, with orders if any
SELECT c.name, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;
-- Asha | 52000
-- Ravi | 1499
-- Meera | NULL ← no orders
Useful trick: find rows with no match
SELECT c.name FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL; -- customers who never ordered
Performance note
Join columns should be indexed (foreign keys usually are). Joins on unindexed columns cause full table scans and slow queries.
What to say in the interview
"INNER JOIN keeps only matching rows from both tables; LEFT JOIN keeps all rows from the left and fills NULLs where the right has no match. Join keys should be indexed to avoid full scans."
More on MySQL
How do you set up MySQL and log in to it?BeginnerHow do you create a database, a table and see data in MySQL?BeginnerHow do you create a MySQL user for an application and give it permissions?BeginnerHow do you back up and restore a MySQL database?BeginnerWhat is a relational database?BeginnerWhat is the difference between a database, a table, a row and a column?Beginner