0

I have written two queries which return the same result, but I want use which is performance wise better

SELECT ID, INTERESTS 
FROM users 
WHERE CITY = (SELECT CITY FROM users WHERE ID = 124)

SELECT b.ID, b.INTERESTS 
FROM users a, users b 
WHERE a.CITY = b.CITY AND a.ID = 124 
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
itech
  • 15
  • 4

2 Answers2

0

First, you should stop using archaic syntax with commas in the FROM clause. Simple rule: Never use commas in the FROM clause; always use explicit JOIN syntax.

Second, a performance question is best handled by checking performance on your data on your system.

Your second query is properly written as:

SELECT b.ID, b.INTERESTS
FROM users a JOIN
     users b 
     ON a.CITY = b.CITY AND a.ID = 124 ;

This should have fine performance. Sometimes EXISTS can have slightly better performance:

select u2.*
from users u
where exists (select 1 from users u where u.city = u2.city and and u.id = 124);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

A couple of thoughts

  1. For your two queries, look at the EXPLAIN plan to see how mysql is limiting the data

You can do this by running

EXPLAIN SELECT ID,INTERESTS FROM users WHERE CITY = (SELECT CITY FROM users WHERE ID=124)
EXPLAIN SELECT b.ID,b.INTERESTS FROM users a,users b WHERE a.CITY = b.CITY AND a.ID=124 

I've found this to be a hepful read when it comes to optimizing queries based on their explain plan.

  1. For good performance, since you are basically joining on the CITY column, consider creating an index on the CITY column in the users table.

Indexes are a trade-off between space and performance.

You can create one by running

CREATE INDEX idx_city ON users(CITY);

Doing this should make both queries perform well.

Community
  • 1
  • 1
Kirk Backus
  • 4,776
  • 4
  • 32
  • 52