Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctionsIndexesPerformance Optimization

MySQL ON Keyword

The `ON` keyword in MySQL is used to specify the condition for joining tables in a `JOIN` clause. It defines how two tables should be related by indicating the common fields between them.

Usage

The `ON` keyword is primarily used in `JOIN` operations to set the condition for merging tables. It directly follows the `JOIN` keyword to establish the link between the tables.

SELECT columns
FROM table1
JOIN table2
ON table1.column_name = table2.column_name;

In this syntax, `ON table1.column_name = table2.column_name` specifies the condition on which the tables are joined. The `ON` keyword can be used with all types of joins, including `INNER JOIN`, `LEFT JOIN`, `RIGHT JOIN`, and more.

Examples

1. Basic Join Condition

SELECT employees.first_name, departments.department_name
FROM employees
JOIN departments ON employees.department_id = departments.department_id;

In this example, the `ON` keyword specifies that the `employees` and `departments` tables should be joined where their `department_id` fields match.

2. Joining with Additional Conditions

SELECT orders.order_id, customers.customer_name
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id AND customers.status = 'active';

This query uses the `ON` keyword with an additional condition to join only active customers with orders.

3. Self Join

SELECT a.employee_id, a.first_name, b.first_name AS manager_name
FROM employees a
JOIN employees b ON a.manager_id = b.employee_id;

This example demonstrates a self join, using the `ON` keyword to relate employees to their managers within the same table.

4. LEFT JOIN Example

SELECT employees.first_name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;

This example shows how the `ON` keyword is used with a `LEFT JOIN` to include all employees, even those not assigned to any department.

Tips and Best Practices

  • Ensure column compatibility. Use the `ON` keyword to join tables with columns that have compatible data types to avoid errors.
  • Use clear aliases. When joining multiple tables, especially with self joins, use table aliases for clarity and brevity.
  • Combine with `WHERE`. After defining relationships with `ON`, further refine results using a `WHERE` clause to filter data.
  • Check join logic. Verify that your `ON` conditions accurately represent the business logic and relationships intended in the database schema.
  • Performance considerations. Index the columns used in the `ON` condition to enhance query performance.
  • Clarify complex conditions. Use parentheses to clarify complex join conditions, especially when multiple conditions are combined.