Performance: LEFT JOIN vs SUBQUERY

sfinks_29

I'm using PostgreSQL 9.3 and have the following tables (simplified to only show the relevant fields):

SITES:
id
name
...

DEVICES:
id
site_id
mac_address UNIQUE
...

Given the mac_address of a particular device, and I want to get the details of the associated site. I have the following two queries:

Using LEFT JOIN:

SELECT s.* FROM sites s
LEFT JOIN devices d ON s.id = d.site_id
WHERE d.mac_address = '00:00:00:00:00:00';

Using SUBQUERY:

SELECT s.* FROM sites s
WHERE s.id IN (SELECT d.site_id FROM devices d WHERE d.mac_address = '00:00:00:00:00:00');

Which of the two queries would have the best performance over an infinitely growing database? I have always leaned towards the LEFT JOIN option, but would be interested to know how the performance of both rates on a large data set.

Craig Ringer

It generally won't make any difference, because they should result in the same query plan. At least, an EXISTS subquery will; IN isn't as always as intelligently optimised.

For the subquery, rather than using IN (...) you should generally prefer EXISTS (...).

SELECT s.*
FROM sites s
WHERE EXISTS (
  SELECT 1
  FROM devices d
  WHERE d.mac_address = '00:00:00:00:00:00'
    AND d.site_id = s.id
);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Left join vs subquery

From Dev

INNER JOIN vs LEFT JOIN performance in SQL

From Dev

Left outer join vs subquery to include departments with no employees

From Dev

MySQL Left Join Subquery with *

From Dev

sql with left join subquery

From Dev

writing a left join as a subquery

From Dev

Left join in subquery

From Dev

Join on field vs join on subquery

From Dev

LEFT OUTER JOIN with subquery syntax

From Dev

SQL SERVER: Left join and subquery

From Dev

LEFT OUTER JOIN with subquery syntax

From Dev

SQL SERVER: Left join and subquery

From Dev

SpringData JPA left join SubQuery

From Dev

Left Join performance on Spanner

From Dev

Simulating FULL OUTER JOIN: Performance of UNION of LEFT+RIGHT JOIN vs cross join

From Dev

Mysql : Left Join and Inner Join in a subquery

From Dev

MySQL left join subquery null join

From Dev

Explain JOIN vs. LEFT JOIN and WHERE condition performance suggestion in more detail

From Dev

Where vs AND in LEFT JOIN

From Dev

Using LINQ left join with multiple conditions and subquery

From Dev

Limit a LEFT JOIN Subquery to 1 result

From Dev

Optimizing SQL subquery through a LEFT JOIN

From Dev

How to fix SQL query with Left Join and subquery?

From Dev

Subquery left join refer to parent ID

From Dev

Left join of subquery not working in SQL Server

From Dev

How to translate this sql to left join without subquery?

From Dev

Count, Group By, Subquery, Left Join not working as expected

From Dev

Mysql Left OUTER JOIN with Subquery (wordpress)

From Dev

Using a Correlated Subquery within a Left Join