JOIN operator in SQL is used to combine rows from two or more tables based on a related column between them. It allows you to retrieve data from multiple tables in a single query, making it a powerful tool for working with relational databases.
Key Points
- Combining Tables:
JOINcombines rows from two or more tables based on a common column. - Types of JOINs: The most common types of
JOINare:INNER JOIN: Returns only matching rows.LEFT JOIN(orLEFT OUTER JOIN): Returns all rows from the left table and matching rows from the right table.RIGHT JOIN(orRIGHT OUTER JOIN): Returns all rows from the right table and matching rows from the left table.FULL JOIN(orFULL OUTER JOIN): Returns all rows when there is a match in either table.CROSS JOIN: Returns the Cartesian product of the two tables (all possible combinations).
- Alias Support: You can use table aliases to simplify queries.
Syntax
column1, column2, ...: The columns you want to retrieve.table1, table2: The tables you want to join.common_column: The column that relates the two tables.
Examples
INNER JOIN
Suppose you have two tables:Employees and Departments.
Table: Employees
Table: Departments
To retrieve employee names along with their department names:
LEFT JOIN
ALEFT JOIN returns all rows from the left table (Employees) and matching rows from the right table (Departments). If there is no match, NULL values are returned for columns from the right table.
If there were employees without a department, their
DepartmentName would appear as NULL.
RIGHT JOIN
ARIGHT JOIN returns all rows from the right table (Departments) and matching rows from the left table (Employees). If there is no match, NULL values are returned for columns from the left table.
If there were departments without employees, the
Name column would appear as NULL.
FULL JOIN
AFULL JOIN returns all rows when there is a match in either table. If there is no match, NULL values are returned for columns from the table without a match.
Query:
If there were employees without departments or departments without employees, the missing values would appear as
NULL.
CROSS JOIN
ACROSS JOIN returns the Cartesian product of the two tables, meaning it combines each row of the first table with each row of the second table.
Practical Use Case
Suppose you have a table namedStudents and another table named Courses.
Table: Students
Table: Courses
To retrieve all possible combinations of students and courses:
Key Takeaways
JOINcombines rows from two or more tables based on a related column.- Common types of
JOINincludeINNER JOIN,LEFT JOIN,RIGHT JOIN,FULL JOIN, andCROSS JOIN. INNER JOINreturns only matching rows, whileLEFT JOINandRIGHT JOINinclude non-matching rows withNULLvalues.CROSS JOINreturns the Cartesian product of the two tables.- Using
JOINallows you to retrieve and analyze data from multiple tables in a single query.