Ali Abbas
Ali Abbas

Reputation: 73

Query Optimization CASE vs UNION

This query returns records of user's friend from friendlist table and then get records of each user from user table.

OPTION # 1

SELECT 
  f.status,
  f.user_to_id,
  f.user_from_id,
  u.user_id,
  u.registration_date,
  u.nickname,
  u.email
FROM ti_friend_list AS f
     LEFT JOIN ti_user u
        ON u.user_id = (CASE f.user_from_id 
                        WHEN 7 THEN f.user_to_id 
                        ELSE f.user_from_id END)
WHERE (f.user_from_id = 7
       OR f.user_to_id = 7) 

OPTION # 2

SELECT 
  f.status,
  f.user_to_id,
  f.user_from_id,
  u.user_id,
  u.registration_date,
  u.nickname,
  u.email
FROM ti_friend_list AS f
  LEFT JOIN ti_user u
    ON u.user_id = f.user_to_id
WHERE f.user_from_id = 7
UNION ALL
SELECT 
  f.status,
  f.user_to_id,
  f.user_from_id,
  u.user_id,
  u.registration_date,
  u.nickname,
  u.email
FROM ti_friend_list AS f
  LEFT JOIN ti_user u
    ON u.user_id = f.user_from_id
WHERE f.user_to_id = 7

Which One is more optimal solution. Basically a comparison between CASE and UNION

Upvotes: 2

Views: 1746

Answers (2)

Brian
Brian

Reputation: 6450

Run them both and see if there's a time difference!

That aside, I would suggest use of the CASE approach is a clearer one in terms of the intention and ease of extension in the future, and I would use that unless you find clear evidence it's not performing. Off the top of my head I think it would be faster though.

Upvotes: 2

boblemar
boblemar

Reputation: 1153

I think like Brian :

  • I think it is more difficult for the engine to optimize a UNION because you can unifiate very different things !
  • The problem with UNION is that you must repeat the SELECT part of the query and don't make mistakes
  • The engine will perform the first part of the union, then the second part and then combine. I think some of the steps will be done twice.

You can try the "explain" command on your queries to see the plan the engine is using.

Upvotes: 2

Related Questions