Back to articles list Articles Cookbook
11 minutes read

What Is CROSS JOIN in SQL?

What is a CROSS JOIN in SQL, and when should you use it? We answer those questions – and give you some examples of CROSS JOIN you can practice for yourself – in this article.

Imagine you're looking through your wardrobe for outfit ideas, wondering which top to wear with which bottom. When you think of the perfect outfit, you envision all of the tops and bottoms in your closet combined. This scenario is similar to SQL CROSS JOIN; one table holds tops and another holds bottoms, and data from both tables is combined to explore all possible pairings.

In this case, a CROSS JOIN serves as the stylist, generating every possible combination of rows from the two datasets. In our wardrobe analogy, one table lists the tops and the other holds the bottoms. By pairing each top with each bottom, you can create a variety of outfit combinations.

But how does this affect data analysis and SQL? CROSS JOINs, a type of SQL JOIN, allow for comprehensive data exploration by creating all possible dataset combinations. This ensures that no potential relationships or interactions are overlooked, yielding a more comprehensive understanding of the data’s interconnections.

For example, as a marketing manager for an e-commerce platform, you may want to provide personalized product recommendations based on customer preferences. Cross-joining product and customer preference datasets produces a comprehensive list of personalized recommendations for each customer, improving marketing precision and sales.

In this article, we'll address all your burning questions about CROSS JOINs. And we'll provide exercises for you to practice on your own. If you're new to JOINs and want to learn more, check out our comprehensive SQL JOINs course, which includes over 90 hands-on exercises on various JOIN types. This interactive course will help you master JOINs, a critical skill for data analysis.

The Basics of CROSS JOIN

To understand the essence of a SQL CROSS JOIN, let's take a look at the basic syntax:

SELECT *
FROM table1
CROSS JOIN table2;

Breakdown:

  • SELECT *: Retrieves all (*) columns from the resulting combined table.
  • FROM table1: Specifies the first table used in the CROSS JOIN operation.
  • CROSS JOIN: Indicates that we want to perform a cross-join operation.
  • table2: Specifies the second table involved in the CROSS JOIN operation.

The syntax is similar to that of any other SQL JOIN. The exception is that a CROSS JOIN requires no join condition – it combines every row from one table with every row from another table, regardless of any specific condition or relationship between the rows. You can find more information about this in Can You Join Two Tables Without a Common Column?

Now let's look at a complete example using the previously-mentioned scenario of your wardrobe. To simplify, imagine that your wardrobe is organized into the two tables below:

Tops

top_itemcolorsize
sweaterredM
shirtblueM
tank_topwhiteS

Bottoms

bottom_itemcolorsize
jeansblueM
skirtblackS
shortsredS

SQL Query:

SELECT *
FROM Tops
CROSS JOIN Bottoms;

Output:

top_itemcolorsizebottom_itemcolorsize
sweaterredMjeansblueM
sweaterredMskirtblackS
sweaterredMshortsredS
shirtblueMjeansblueM
shirtblueMskirtblackS
shirtblueMshortsredS
tank_topwhiteSjeansblueM
tank_topwhiteSskirtblackS
tank_topwhiteSshortsredS

In this simple example, the CROSS JOIN connects each type of top to each type of bottom, allowing you to see every outfit combination in your wardrobe. This feature allows you to more effectively plan your outfits or experiment with new ideas by taking into account all possible combinations.

Notice that since the Tops table has 3 rows and the Bottoms table has 3 rows, the resulting table has 9 (3 times 3) rows. This multiplication principle applies across all CROSS JOIN operations. For more examples, check out our Illustrated Guide to the SQL CROSS JOIN.

What Is a Cartesian Product?

A Cartesian product, a mathematical concept introduced by René Descartes, is the result of pairing each element of one set with every element of another. In essence, it is equivalent to creating all possible combinations of two or more sets, resulting in the combination of elements from each.

In SQL, the CROSS JOIN operation delivers the Cartesian product between two tables. It combines every row from the first table with each row from the second table, resulting in a new table in which each row represents a fusion of elements from both tables. Effectively, CROSS JOIN orchestrates the generation of all possible combinations of rows from the two tables, resulting in the Cartesian product.

Practical Applications: SQL CROSS JOIN in Action

Now, let's apply what we've learned with some examples of how CROSS JOIN can help with database management.

Exercise 1: Product Variants

Context:

Your manager wants to expand the e-commerce platform's product offerings and offer customers a more diverse shopping experience. They have given you two tables: colors (which contains various colors) and sizes (which contains different sizes) for a specific product. Your task is to combine the data from both tables to generate comprehensive product variants that include all columns from both tables.

SQL Query:

SELECT *
FROM colors
CROSS JOIN sizes;

Query Result:

This query will return all columns from the colors and sizes tables. This exercise facilitates the creation of product variants, allowing customers to select from a variety of options. Displaying all possible combinations of colors and sizes improves the customer shopping experience and increases the likelihood of a customer finding the desired product variant.

Exercise 2: Appointment Time Slots

Context:

Your task in the appointment booking app is to efficiently schedule appointments. Your manager has given you three tables:

  • days, contains the available days under the column day.
  • times, which contain all available times under the column time.
  • employees, which contains employee information, including the employee_name.

Your task is to create comprehensive time slots using these three tables with the day, time, and employee name.

SQL Query:

SELECT 
  days.day, 
  times.time, 
  employees.employee_name
FROM days
CROSS JOIN times
CROSS JOIN employees;

Query Result:

This query will return all columns from the days, times, and employees tables. This exercise helps create comprehensive time slots by taking into account the days, times, and employees. It ensures effective appointment scheduling, optimizes resource allocation, and enhances customer service.

Exercise 3: Product Bundling for Promotion

Context:

In a retail setting, your manager aims to boost sales by promoting attractive product bundles. You're given two tables:

  • office_supplies, which contains the columns product_id, product_name, price, and color.
  • electronics, which contains the columns product_id, product_name, price, and brand.

The goal is to create appealing product bundles by pairing items from these tables, with the additional criterion that the price of the office supplies should be less than $50. The output should include the product ID, name, and price for both categories.

SQL Query:

SELECT 
  o.product_id AS office_supplies_id, 
  o.product_name AS office_supplies_name, 
  o.price AS office_supplies_price,
  e.product_id AS electronics_id, 
  e.product_name AS electronics_name, 
  e.price AS electronics_price
FROM office_supplies o
CROSS JOIN electronics e
WHERE o.price < 50;

Query Result:

This query returns a result set with the product ID, name, and price from both tables, with the additional criterion that office supplies should be under $50.

This comprehensive list makes it easier to create appealing product bundles by combining items from different categories while also keeping office supplies affordable. It enables retailers to offer bundled promotions that combine low-cost office supplies and electronics, providing customers with a variety of practical solutions. This strategic approach reflects consumer preferences and has the potential to significantly increase sales and customer satisfaction.

CROSS JOIN Exercises

In this section, we will provide interactive exercises that you can complete on your own using CROSS JOINs. Each exercise comes with its own context and tables. Try solving them for yourself, then click to reveal the solutions. You can take a look at our SQL JOIN Cheat Sheet for assistance. Let’s get started:

Exercise 1: Meal Planning

You manage a service that provides customers with a variety of meal plans. Your goal is to pair main dishes with appropriate side dishes to provide a variety of meal choices.

Given the tables listing available main dishes and side dishes, your output should contain all possible combinations of only the column dish_name from the mains table and the dish_name column from the side_dishes table.

mains

dish_iddish_name
101Tofu Curry
102Chicken Curry
103Veggie Stir-fry

side_dishes

dish_iddish_name
201Rice
202Chips

SQL Query:

SELECT 
  m.dish_name AS main_dish, 
  s.dish_name AS side_dish
FROM mains m
CROSS JOIN side_dishes s;

Output:

main_dishside_dish
Tofu CurryRice
Tofu CurryChips
Chicken CurryRice
Chicken CurryChips
Veggie Stir-fryRice
Veggie Stir-fryChips

Using CROSS JOIN to combine main dishes with appropriate side dishes, you can create a wide range of meal options. This approach enables the meal planning service to provide more combinations to their customers.

Exercise 2: Project Assignment

As a project manager, you must assign an employee to various projects based on their training status. Only employees who have received specialized training can be assigned to the projects.

You are given two tables, one listing the available projects and the other with the employees' training status. If an employee has not received training, they cannot be assigned to the project. Your output should include the project ID from the projects table and the employee ID and name from the employees table.

projects

project_idproject_name
101Project X
102Project Y

employees

employee_idemployee_namereceived_training
201JohnYes
202EmilyNo
203SarahYes

SQL Query:

SELECT 
  p.project_id, 
  e.employee_id, 
  e.employee_name
FROM projects p
CROSS JOIN employees e
WHERE e.received_training = 'Yes';

Output:

project_idemployee_idemployee_name
101201John
101203Sarah
102201John
102203Sarah

By utilizing CROSS JOIN and appropriate filtering, all combinations of projects and the employees with the necessary training are displayed.

Exercise 3: Premium Product Recommendations

As an e-commerce manager, you want to recommend premium products to customers with Gold subscription status and improve their shopping experience with exclusive offerings.

You have two tables, one for customers and their subscription statuses and another for premium products. Your goal is to show all the possible combinations of customers who have gold subscription status with premium products, allowing for personalized recommendations. Your output should include a list of all possible combinations of customer ID, product ID, and product name. You will be working with the following tables:

customers

customer_idsuscription_status
111Gold
112Silver
113Bronze
114Gold

premium_products

product_idproduct_name
101Diamond Watch
102Platinum Ring

SQL Query:

SELECT 
  c.customer_id, 
  p.product_id, 
  p.product_name
FROM customers c
CROSS JOIN premium_products p
WHERE c.suscription_status = 'Gold';

Output:

customer_idproduct_idproduct_name
111101Diamond Watch
111102Platinum Ring
114101Diamond Watch
114102Platinum Ring

Using CROSS JOIN and filtering, customers with a Gold subscription status are efficiently matched with premium products. This facilitates personalized recommendations, which improve the shopping experience for these valued customers.

If you’ve enjoyed these practice exercises, why not check out our article SQL Joins: 12 Practice Questions with Detailed Answers, where you'll find even more helpful exercises to boost your SQL skills!

Performance Considerations for CROSS JOIN

When using CROSS JOIN in SQL, it is critical to consider the performance implications, particularly given the potentially massive result set generated by an unrestricted CROSS JOIN. This operation produces a Cartesian product that grows exponentially in proportion to the size of the input tables. Let's look at some tips for avoiding performance issues.

  • Limit the size of input tables: Before executing a CROSS JOIN, refine the input tables by applying appropriate filters. Use WHERE clauses or subqueries to narrow down the dataset, thus minimizing the number of rows to be combined.
  • Apply additional filtering: After the CROSS JOIN, employ supplementary filtering conditions to further refine the result set. This aids in reducing the final output's size and focusing solely on pertinent data, enhancing query performance.
  • Consider alternative join types: Evaluate whether an unrestricted CROSS JOIN is truly indispensable. Depending on specific requirements, explore alternative join types like INNER JOIN, LEFT JOIN, or RIGHT JOIN, which may be more efficient and more tailored to your needs.
  • Optimize query execution: Ensure that your database is optimized for efficient query execution. Implementing indexes, particularly on join columns, will expedite performance – especially when handling extensive datasets.

By incorporating these performance considerations for the use of CROSS JOIN, you can mitigate undue strain on your database and ensure the smooth execution of queries, even when working with extensive datasets.

Want to Learn More About SQL CROSS JOINs?

In conclusion, CROSS JOIN in SQL is a useful tool for creating comprehensive datasets by combining every row from one table with every row from another. By understanding the fundamentals of CROSS JOIN and considering its performance implications, analysts can unleash its full potential for exploring complex relationships within datasets and extracting valuable insights.

To fully leverage the capabilities of CROSS JOIN and other SQL JOIN types, LearnSQL.com has created the SQL JOINs course. This interactive course includes hands-on exercises covering various JOIN types and is designed to help you understand the complexities of JOIN operations.

You can also read other articles on our blog, such as The Top 10 SQL JOIN Interview Questions and How to Answer Them. And don't forget about our handy SQL JOIN Cheat Sheet, which is always available to assist you in your SQL exploration. So, what are you waiting for? Elevate your skills today!