Sobes.tech
Junior

What is the difference between RIGHT JOIN, LEFT JOIN, and INNER JOIN?

sobes.tech AI

Answer from AI

  • INNER JOIN: Returns rows only if matching values exist in both tables.
  • LEFT JOIN: Returns all rows from the left table and matching rows from the right. If there are no matches, NULL values are returned for columns from the right table.
  • RIGHT JOIN: Returns all rows from the right table and matching rows from the left. If there are no matches, NULL values are returned for columns from the left table.

Example in SQL:

-- Table users
CREATE TABLE users (
    user_id INT PRIMARY KEY,
    username VARCHAR(50)
);

INSERT INTO users (user_id, username) VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Charlie');

-- Table orders
CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    user_id INT,
    product VARCHAR(50)
);

INSERT INTO orders (order_id, user_id, product) VALUES
(101, 1, 'Laptop'),
(102, 2, 'Mouse'),
(103, 1, 'Keyboard');
-- INNER JOIN: Will return Alice (Laptop, Keyboard) and Bob (Mouse)
SELECT u.username, o.product
FROM users u
INNER JOIN orders o ON u.user_id = o.user_id;
-- LEFT JOIN: Will return Alice (Laptop, Keyboard), Bob (Mouse), and Charlie (NULL)
SELECT u.username, o.product
FROM users u
LEFT JOIN orders o ON u.user_id = o.user_id;
-- RIGHT JOIN: Will return Alice (Laptop, Keyboard), Bob (Mouse)
-- (If there were records in orders without user_id, they would also be returned)
SELECT u.username, o.product
FROM users u
RIGHT JOIN orders o ON u.user_id = o.user_id;