Jason Fox

Icon

programming, products, and pontifications…

Rewriting Sub-selects as Joins

Your RDBMS will usually rewrite your sub-selects behind the scenes as joins.  However, there are times where you’ll want to do this yourself.  For example, past versions of MySQL did not play well with sub-selects.  Here are a couple examples of how to rewrite sub-selects as joins.

select *
from   table_a
where  id not in (select a_id from table_b);
-- can be rewritten as...
select *
from   table_a
left   outer join table_b on table_a.id = table_b.a_id
where  table_b.a_id is null;

select *
from   table_a
where  id in (select a_id from table_b);
-- can be rewritten as...
select *
from   table_a
left outer join table_b on table_a.id = table_b.a_id
where  table_b.a_id is not null;

Category: Programming

Tagged: ,

Leave a Reply

About

Jason Fox is the Co-Founder of Initiate Commerce, Inc. and the Head of Technology and Development at readMedia, Inc. Jason has over 10 years experience designing and building scalable, internet-based, applications for start-up companies both large and small.

Twitter

    github.com/jfoxny

    • No feed items.

    Recent Wines

    View Jason Fox's profile on LinkedIn
    Jason Fox's Facebook profile