1

Assume that we have two tables in SQL database (I'm using PostgreSQL in case the answer depends on the database):

CREATE TABLE testA ( id integer, checked boolean ) CREATE TABLE testB ( id integer, testA_id integer ) 

I want to do a select from testB joined with testA and get all results which are checked. There are two ways:

SELECT tA.*, tB.* FROM testB AS tB JOIN testA AS tA ON (tA.id = tB.testA_id AND tA.checked) 

or

SELECT tA.*, tB.* FROM testB AS tB JOIN testA AS tA ON tA.id = tB.testA_id WHERE tA.checked 

Which way is preferred? And are there performance differences?

2 Answers 2

4

Well, the WHERE clause filters the results. The ON just defines the way the tables are joined together. In your example there would be no difference.

But take a look at the following:

CREATE TABLE testA ( id integer, checked boolean ) CREATE TABLE testB ( id integer, testA_id integer, checked boolean ) 

As you can see i have added a checked column in TestB.

There might be rows in TableA that have no rows in TableB Like the following data:

TestA

ID|checked 1|true 2|true 3|false 

TestB

ID|testA_id|checked 1|1|true 2|1|false 3|3|true 

As you can see there is no TestB for TestA id = 2

Now, let's assume you want to display ALL TestA rows along with the checked TableB rows (if any).

So you need a left join:

First Case

SELECT tA.*, tB.* FROM testB AS tB LEFT JOIN testA AS tA ON (tA.id = tB.testA_id AND tB.checked) 

Reults

ID|checked|ID|testA_id|checked 1|true|1|1|true 2|true|null|null|null 3|false||3|3|true 

ID 1, 2 and 3 of TableA is returned and if there is a checked TableB row then we return that too.

Second Case

SELECT tA.*, tB.* FROM testB AS tB LEFT JOIN testA AS tA ON tA.id = tB.testA_id WHERE tB.checked 

Reults

ID|checked|ID|testA_id|checked 1|true|1|1|true 3|false||3|3|true 

In this case only IDs 1 and 3 are returned because we filter the results to show only the ones that have TableB checked.

Sign up to request clarification or add additional context in comments.

Comments

1

No performance differences, the optimizer takes care of it, so the two queries are actually the same. You can confirm by using EXPLAIN on your query.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.