WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

MySQL · Intermediate · question 35 of 100

What is the difference between a self-join and a cross join in MySQL?

📕 Buy this interview preparation book: 100 MySQL questions & answers — PDF + EPUB for $5

In MySQL, self-join and cross join are two different types of joins used to combine data from two or more tables.

A self-join is a join in which a table is joined with itself. It is used when we want to combine rows from the same table based on some condition. In other words, it is a way of joining a table with itself. Self-joins are useful when we have a table that contains hierarchical data, such as an organization chart, where each row contains a reference to a parent row in the same table.

For example, suppose we have a table named employees with columns EmployeeId, EmployeeName, and ManagerId. The ManagerId column contains the EmployeeId of the employee’s manager. To find the name of the manager of each employee, we can use a self-join as follows:

SELECT e.EmployeeName, m.EmployeeName as ManagerName
FROM employees e 
JOIN employees m ON e.ManagerId = m.EmployeeId;

Here, we are joining the employees table with itself using the ManagerId and EmployeeId columns.

On the other hand, a cross join is used to combine all possible rows from two or more tables. It is also known as a Cartesian product because it generates a result set that contains all possible combinations of rows from the participating tables. In other words, it produces the cross product of the two tables.

For example, suppose we have two tables named colors and sizes, which contain the following data:

colors table:

| color |
|-------|
| red   |
| green |
| blue  |

sizes table:

| size |
|------|
| S    |
| M    |
| L    |

To generate a result set that contains all possible combinations of colors and sizes, we can use a cross join as follows:

SELECT * FROM colors CROSS JOIN sizes;

The result of this query will be a table with all possible combinations of rows from the colors and sizes tables:

| color | size |
|-------|------|
| red   | S    |
| red   | M    |
| red   | L    |
| green | S    |
| green | M    |
| green | L    |
| blue  | S    |
| blue  | M    |
| blue  | L    |

In summary, the main difference between a self-join and a cross join is that a self-join is used to join a table with itself, while a cross join is used to generate a Cartesian product of two or more tables.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic MySQL interview — then scores it.
📞 Practice MySQL — free 15 min
📕 Buy this interview preparation book: 100 MySQL questions & answers — PDF + EPUB for $5

All 100 MySQL questions · All topics