Welcome to the SQL CROSS JOIN tutorial! In this lesson, we'll dive deep into one of the most powerful SQL operators, the CROSS JOIN. Let's get started! š
A CROSS JOIN, also known as the Cartesian product, combines every row from two or more tables, creating a new table with the result of the multiplication of rows from each table. It doesn't use any join condition, which makes it quite different from other SQL join types.
š” Pro Tip: While CROSS JOIN can be useful, it often produces large results, so it should be used sparingly and only when needed.
The basic syntax for a CROSS JOIN is as follows:
SELECT column1, column2, ...
FROM table1
CROSS JOIN table2;Let's demonstrate CROSS JOIN using two tables: employees and departments.
-- Employees table
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(255),
department_id INT
);
INSERT INTO employees (id, name, department_id)
VALUES
(1, 'Alice', 101),
(2, 'Bob', 102),
(3, 'Charlie', 103);
-- Departments table
CREATE TABLE departments (
id INT PRIMARY KEY,
name VARCHAR(255)
);
INSERT INTO departments (id, name)
VALUES
(101, 'HR'),
(102, 'IT'),
(103, 'Sales');Now, let's perform a CROSS JOIN between these two tables:
SELECT employees.name, departments.name AS department
FROM employees
CROSS JOIN departments;The output will be:
| name | department |
|--------|--------------|
| Alice | HR |
| Alice | IT |
| Alice | Sales |
| Bob | HR |
| Bob | IT |
| Bob | Sales |
| Charlie| HR |
| Charlie| IT |
| Charlie| Sales |
As you can see, every employee has been paired with each department, creating a Cartesian product.
The main difference between CROSS JOIN and INNER JOIN is that CROSS JOIN produces a Cartesian product of both tables, while INNER JOIN only returns rows where the join condition is met.
Let's create a new table, employee_salaries, to demonstrate this:
-- Employee Salaries table
CREATE TABLE employee_salaries (
id INT PRIMARY KEY,
employee_id INT,
salary DECIMAL(10, 2)
);
INSERT INTO employee_salaries (id, employee_id, salary)
VALUES
(1, 1, 50000),
(2, 2, 60000),
(3, 3, 70000);Now, let's perform an INNER JOIN between the employees and employee_salaries tables using the employee_id:
SELECT employees.name, employee_salaries.salary
FROM employees
INNER JOIN employee_salaries ON employees.id = employee_salaries.employee_id;The output will be:
| name | salary |
|--------|--------|
| Alice | 50000 |
| Bob | 60000 |
| Charlie | 70000 |
As you can see, the INNER JOIN only returns rows where the employee_id matches between the employees and employee_salaries tables.
What is the difference between CROSS JOIN and INNER JOIN in SQL?
In this tutorial, we've learned about SQL CROSS JOIN, its syntax, and practical examples. We've also compared it with INNER JOIN to understand its unique features. Remember to use CROSS JOIN sparingly and only when needed, as it can generate large results. Keep practicing, and you'll master SQL join operations in no time!
Happy coding! š»š