cross apply example

Cross Apply Example: A Comprehensive Tutorial

By Richard Lopez
AD

Cross apply is a SQL operator that allows you to combine rows from two or more tables based on a related column between them. It's particularly useful when you need to retrieve data that doesn't directly exist in a single table. Here's a comprehensive guide with examples to help you understand and implement cross apply in your SQL queries.

Before diving into examples, let's understand the basic syntax of cross apply. The syntax looks like this:

Understanding Cross Apply

Cross apply is an outlier among the traditional joins (inner, outer, left, right) as it doesn't require a common column between the left and right tables. Instead, it uses the OUTPUT clause to generate values on the right side and join them with the left side based on a condition.

AD
Cross text symbol
Cross text symbol
an image of a computer screen with numbers and other items in the table below it
an image of a computer screen with numbers and other items in the table below it
an old, black and white paper with writing on the bottom corner in cursive handwriting
an old, black and white paper with writing on the bottom corner in cursive handwriting

Here's a simple example that demonstrates the concept:

Cross Apply Syntax Breakdown

Let's break down the cross apply syntax using a simple example:

Cross ⸸✞☦✝✟♱☥♁✙⚰️⛧ (emoji text symbol copy paste)
Cross ⸸✞☦✝✟♱☥♁✙⚰️⛧ (emoji text symbol copy paste)
the cross symbols are shown in black and white, with different names on each one
the cross symbols are shown in black and white, with different names on each one
a cross with the words two sides of the cross
a cross with the words two sides of the cross
SELECT t1.col1, t2.col2 FROM Table1 AS t1 CROSS APPLY (SELECT col2 FROM Table2 WHERE t1.common_field = t2.common_field) AS t2

Comparing Cross Apply and Inner Join

Cross apply is often confused with inner join, but they operate quite differently. An inner join combines rows based on a matching column, while cross apply allows you to reference one table's columns (t1) inside the implicit subquery (t2), creating a join based on rows that match the implicit WHERE clause.

Cross Apply vs. Outer Apply

Outer apply is another similar operator that extends the functionality of cross apply by allowing Cartesian products from the left table. The primary difference lies in how they handle right-side record return when there's no match on the left side.

AD

When to Use Cross Apply

Cross apply shines in situations where you need to access multiple subqueries or correlation columns in the FROM clause, making it perfect for accessing related data that doesn't directly exist in a single table.

a cross that has been cut out to be used as a coloring page for children
a cross that has been cut out to be used as a coloring page for children
Cognitive Behavioral Model
Cognitive Behavioral Model
How to Make a Palm Cross (Easy Palm Cross Instructions!)
How to Make a Palm Cross (Easy Palm Cross Instructions!)
Free Printable Cross Outlines & Templates
Free Printable Cross Outlines & Templates
the crucifix with jesus's face on it is black and white
the crucifix with jesus's face on it is black and white
How to Draw a Cross: Easy Step-by-Step Cross Drawing Tutorial for Beginners
How to Draw a Cross: Easy Step-by-Step Cross Drawing Tutorial for Beginners

Cross Apply vs. JOIN

In comparison, join operators only work with a single table and are explicitly limited to joining on a single common column. Cross apply, on the other hand, can join multiple tables on multiple conditions simultaneously.

Real-world Cross Apply Examples

Now that we've discussed the theory let's dive into some real-world examples to solidify your understanding.

AD

Example 1: Rating System

Consider a rating system where users can rate movies. You want to retrieve the list of movies along with their average rating and the total number of ratings.

a cross with arrows pointing to the center and an arrow at the bottom is shown
a cross with arrows pointing to the center and an arrow at the bottom is shown
the diagram shows how to draw a cross
the diagram shows how to draw a cross
FREE Easter Cross Template Printable for Kids (PDF) (2024)
FREE Easter Cross Template Printable for Kids (PDF) (2024)
SELECT m.movie_id, m.title, AVG(r.rating) AS average_rating, COUNT(r.rating_id) AS total_ratings FROM movies AS m CROSS APPLY (SELECT rating FROM ratings WHERE m.movie_id = r.movie_id) AS r GROUP BY m.movie_id, m.title

Example 2: Shipping Cost Calculation

Imagine an e-commerce website where shipping cost depends on the total weight of the items in the cart and the destination. To calculate the shipping cost, you need to combine data from multiple tables: cart_items, items (for weight), and destinations (for shipping fees).

SELECT ci.cart_id, d.destination, SUM(i.weight * ci.quantity) AS total_weight, (SELECT shipping_fee FROM destinations WHERE destination = d.destination) AS shipping_fee FROM cart_items AS ci CROSS APPLY (SELECT weight FROM items WHERE item_id = ci.item_id) AS i CROSS APPLY (SELECT d.destination FROM destinations WHERE d.destination = ci.destination) AS d GROUP BY ci.cart_id, d.destination

In conclusion, cross apply is a powerful SQL operator that expands your capabilities to join tables and access related data. It's an essential tool for any developer looking to enhance their SQL skills and unlock more complex queries. Practice with these examples, and you'll soon find many more use cases for cross apply in your projects.

AD
AD