Tags
MySQL , Sql
Asked 8 years ago
20 Dec 2016
Views 894
jaman

jaman posted

differnece between where clause and on clause in SQL join ?

i want to list course name form the table course with student info.
student_id is foreign key at course table , id is primary key at student table.

i did it with join in "where clause"


select c.name from student as s , course c where c.student_id= s.id  


and doing same with "on clause"

select name from student as s join  course c on c.student_id= s.id  


i got same result for both query.

so what is difference between where clause and on clause in SQL join , whats is pros and cons of " where clause" vs "on clause" in SQL join

currently dealing with MySQL but SQL , PostgreSQL all have same story i think,
steave

steave
answered Apr 24 '23 00:00

The WHERE clause filters rows from a result set after a JOIN operation has been performed. It applies to the result set of the JOIN and can reference columns from any table in the JOIN. Typically, the WHERE clause is used to impose additional conditions beyond the join conditions.

For instance, consider the query below that joins two tables, orders and customers , using the customer_id column:



SELECT *
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id
WHERE orders.status = 'shipped'

In this query, the join condition is specified in the ON clause, which states that the customer_id column in the orders table must match the customer_id column in the customers table. The WHERE clause is then used to further filter the result set by specifying that only orders with a status of 'shipped' should be included.

The ON clause, on the other hand, is used to specify the join condition between two tables. It joins rows from two tables based on a common column or set of columns. The ON clause is typically used in INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN statements.

For example, consider the query below that joins two tables, orders and customers , using the customer_id column:



SELECT *
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id

In this query, the join condition is specified in the ON clause, which states that the customer_id column in the orders table must match the customer_id column in the customers table. The result set will include all rows from both tables where the join condition is true.

To summarize, the WHERE clause filters the result set after a JOIN operation, while the ON clause specifies the join condition between two tables.
Post Answer