When Should We Use CROSS APPLY Over INNER JOIN?
Last Updated :
20 Sep, 2024
In SQL Server, both INNER JOIN
and CROSS APPLY
are used to combine data from multiple tables, but they serve different purposes and have distinct use cases. INNER JOIN
is typically used to match rows between two tables based on a related column, returning only the rows where a match exists in both tables.
On the other hand, CROSS APPLY
allows for more flexibility, especially in scenarios that require row-wise operations or dynamic subqueries for each row. In this article, When should we use CROSS APPLY over INNER JOIN in detail by understanding various examples and so on.
Understanding INNER JOIN
INNER JOIN
in SQL Server is used to combine rows from two or more tables based on a related column between them. It returns only the rows where there is a match found in both tables.
The syntax for INNER JOIN
in SQL Server is as follows:
SELECT column1, column2, ...
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Understanding CROSS APPLY
CROSS APPLY
is a specific feature in SQL Server that is especially useful when dealing with table-valued functions or correlated subqueries. It allows row-wise operations and can apply subqueries dynamically for each row from the outer table.
The syntax for CROSS APPLY
in SQL Server is as follows:
SELECT column_list
FROM outer_table
CROSS APPLY (
-- Subquery or table-valued function
inner_table_expression
) AS alias;
Setting Up Environment
For fully understanding CROSS APPLY
and INNER JOIN
in SQL Server, we will create 2 tables, write queries, and understand the output one by one.
-- Creating the 'employees' table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
department_id INT
);
-- Creating the 'departments' table
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(100)
);
-- Inserting data into the 'employees' table
INSERT INTO employees (employee_id, name, department_id)
VALUES (1, 'John Doe', 1),
(2, 'Alice Johnson', 2),
(3, 'Michael Brown', 1);
-- Inserting data into the 'departments' table
INSERT INTO departments (department_id, department_name)
VALUES (1, 'HR'),
(2, 'Engineering');
Example of When to Use CROSS APPLY
Over INNER JOIN
in SQL Server
Example 1: INNER JOIN
to Retrieve Employees with Their Department Names
In this example, we will combine data from the employees and departments tables using INNER JOIN.
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;
Output:
name | department_name |
---|
John Doe | HR |
Alice Johnson | Engineering |
Michael Brown | HR |
Explanation: In this example the query uses an INNER JOIN
to combine data from the employees
and departments
tables based on their department_id
. It retrieves the names of employees along with the names of the departments they belong to.
Example 2: INNER JOIN
with Conditions
In this example, we use INNER JOIN
with a filter to get the names of employees related to a particular department.
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id
WHERE departments.department_name = 'HR';
Output:
name | department_name |
---|
John Doe | HR |
Michael Brown | HR |
Explanation: In this we apply an INNER JOIN
between employees
and departments
, but with a condition to filter the results. This query retrieves the names of employees who belong to the 'HR' department.
Example 3: CROSS APPLY
to Retrieve Employees with Department Info
In this example, we will use CROSS APPLY
to get the employees with their department details.
SELECT employees.name, department_info.department_name
FROM employees
CROSS APPLY (
SELECT department_name
FROM departments
WHERE employees.department_id = departments.department_id
) AS department_info;
Output:
name | department_name |
---|
John Doe | HR |
Alice Johnson | Engineering |
Michael Brown | HR |
Explanation: In this the query uses a CROSS APPLY
operation, allowing us to correlate the employees
and departments
tables row by row. It retrieves all employees along with their corresponding department names.
Example 4: CROSS APPLY
with Conditions
In this example, we will filter the results obtained from CROSS APPLY
based on conditions.
SELECT employees.name, department_info.department_name
FROM employees
CROSS APPLY (
SELECT department_name
FROM departments
WHERE employees.department_id = departments.department_id
AND departments.department_name = 'HR'
) AS department_info;
Output:
name | department_name |
---|
John Doe | HR |
Michael Brown | HR |
Explanation: Here, we use CROSS APPLY
with conditions to filter the results. This query retrieves the names of employees who belong to the 'HR' department only.
Conclusion
While both INNER JOIN
and CROSS APPLY
are powerful tools in SQL Server, they are suited for different types of operations. INNER JOIN
is ideal for combining datasets based on common keys and returning matching rows. However, when dealing with dynamic subqueries or operations that need to be applied on a row-by-row basis, CROSS APPLY
offers a more flexible and efficient solution.
Similar Reads
When should we use CROSS APPLY over INNER JOIN in MySQL
CROSS APPLY and INNER JOIN are used in MySQL to combine data from multiple tables. When dealing with row-wise operations or dynamic subqueries, CROSS APPLY is more efficient than INNER JOIN. CROSS APPLY allows for more detailed control on individual rows, while INNER JOIN operates on sets of data. I
4 min read
CROSS APPLY vs INNER JOIN in PL/SQL
PL/SQL Stands for procedural language extension to SQL. In a procedure, the role of the subprogram is to perform a particular task and it is a unit module of a program. It combined to form larger programs. A subprogram can be involved by another program which is called the calling program. PL/SQL pr
6 min read
INNER JOIN ON vs WHERE clause in SQL Server
In SQL Server, joining tables and filtering data are essential for retrieving meaningful information. The INNER JOIN operation is used to combine rows from multiple tables based on a matching condition, while the WHERE clause allows for further filtering of results. In this article, we will PL/SQL S
7 min read
How to Delete using INNER JOIN with SQL Server?
In SQL Server, we can use INNER JOIN within a DELETE statement to remove data from one table based on matching records in another table. This method is useful when we need to delete records from a target table that have corresponding rows in another table.Understanding DELETE with INNER JOINUndersta
4 min read
SQL Full Outer Join Using Where Clause
SQL (Structured Query Language) provides powerful tools to manage and query relational databases. One of its most flexible features is the JOIN operation, which allows combining data from two or more tables based on related columns. Among the various types of joins, the FULL OUTER JOIN is particular
4 min read
INNER JOIN ON vs WHERE clause in MySQL
When working with MySQL queries that involve multiple tables, understanding how to effectively use INNER JOIN ON versus the WHERE clause can significantly impact query performance and clarity. These two SQL constructs serve distinct purposes in combining data from different tables based on specific
5 min read
When to Use @JoinColumn Annotation in Hibernate?
The @JoinColumn annotation in Hibernate is used to specify the mapping of a foreign key column in a relationship between two entities. The @JoinColumn annotation is applied on the owning side of the association to define the foreign key column name and other attributes which are related to the join
3 min read
Subqueries in the WHERE Clause of UPDATE in SQL
In SQL, an UPDATE statement modifies existing records in a table. When updating records, we can use a subquery within the WHERE clause to conditionally update only specific rows based on results from another query. In this article, we will learn how to write Subqueries in the WHERE Clause to Update
4 min read
SQL Query to Find the Sum of all Values in a Column
In SQL, calculating the sum of values in a column is a crucial task for performing data analysis and generating reports. The SUM() function helps to calculate the total sum of numeric values from a column, which is especially useful in scenarios like finding total sales, total employees, or total re
5 min read
FULL OUTER JOIN in SQLite
In the area of data querying and manipulation, the ability to combine information from different sources is important. SQLite, a popular embedded database engine, offers a range of join operations to fast process. One such operation FULL OUTER JOIN is particularly powerful as it allows us to merge d
4 min read