SELECT CASE WHEN useridfrom > useridto THEN '' || useridfrom || '-' || useridto ELSE '' || useridto || '-' || useridfrom END AS convo_signature, max(id) as id, timecreated FROM (SELECT id, useridfrom, useridto, timecreated FROM mdl_message WHERE (useridto = 896 AND timeusertodeleted = 0 AND notification = 0) OR (useridfrom = 29 AND timeuserfromdeleted = 0 AND notification = 0) AND timecreated = 1486606496 UNION ALL SELECT id, useridfrom, useridto, timecreated FROM mdl_message_read WHERE (useridto = 896 AND timeusertodeleted = 0 AND notification = 0) OR (useridfrom = 29 AND timeuserfromdeleted = 0 AND notification = 0) AND timecreated = 1486606496) x WHERE (CASE WHEN useridfrom > useridto THEN '' || useridfrom || '-' || useridto ELSE '' || useridto || '-' || useridfrom END = '4-3' AND timecreated = 1486606496) GROUP BY CASE WHEN useridfrom > useridto THEN '' || useridfrom || '-' || useridto ELSE '' || useridto || '-' || useridfrom END, timecreated Empty set (51.87 sec) +----+--------------+------------------+-------------+----------------------------------------------------------------------------------------------------------+-------------------------------------------------+---------+-------+--------+--------------------------------------------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+--------------+------------------+-------------+----------------------------------------------------------------------------------------------------------+-------------------------------------------------+---------+-------+--------+--------------------------------------------------------------------------------+ | 1 | PRIMARY | | ref | | | 8 | const | 10 | Using where; Using temporary; Using filesort | | 2 | DERIVED | mdl_message | index_merge | mdl_mess_useusetimtim_ix,mdl_mess_usetimnot_ix,mdl_mess_usetimnot2_ix | mdl_mess_usetimnot2_ix,mdl_mess_useusetimtim_ix | 18,8 | NULL | 2 | Using sort_union(mdl_mess_usetimnot2_ix,mdl_mess_useusetimtim_ix); Using where | | 3 | UNION | mdl_message_read | ref | mdl_messread_nottim_ix,mdl_messread_useusetimtim_ix,mdl_messread_usetimnot_ix,mdl_messread_usetimnot2_ix | mdl_messread_nottim_ix | 2 | const | 740803 | Using where | | NULL | UNION RESULT | | ALL | NULL | NULL | NULL | NULL | NULL | Using temporary | +----+--------------+------------------+-------------+----------------------------------------------------------------------------------------------------------+-------------------------------------------------+---------+-------+--------+--------------------------------------------------------------------------------+ 4 rows in set (0.00 sec)