title: Simplify UNION query that overwrites duplicate rows
body: <pre><code>create table sections(
    id serial,
    section_name char(255) not null,
    version_id int not null
  );
  
  create table section_versions(
   id int primary key not null,
   version_name char(255) not null  
  );
  
  insert into section_versions(id, version_name)
  values (1, 'default'), (2, 'version A'), (3, 'version B');
  
  insert into sections(section_name, version_id)
  values ('Toys', 1), ('Animals', 1), ('Cars', 1),
         ('Toys', 2), ('Animals', 2), ('Instruments', 2),
         ('Toys', 3);
  </code></pre>
  
  <p>I need to select <strong>sections</strong> based on requested <strong>section_version.version_name</strong>.</p>
  
  <p>If the <strong>version_name</strong> is <strong>"default"</strong>, then query just need to return all <strong>sections</strong> which have <strong>"default"</strong> version.</p>
  
  <p>But if the <strong>"version A"</strong> was requested, then it should return every <strong>section</strong> that belongs to <strong>"version A"</strong>, and add a missing sections from <strong>"default"</strong> version - basing on <strong>section_name</strong>.</p>
  
  <p><strong>Please see this fiddle:</strong> <a href="http://sqlfiddle.com/#!15/466e1/1/0" rel="nofollow">http://sqlfiddle.com/#!15/466e1/1/0</a></p>
  
  <p>Here's what I came up with:</p>
  
  <pre><code>select * from sections
  join section_versions on (section_versions.id = sections.version_id)
  where section_versions.version_name = 'default'
  
  and sections.section_name not in (
    select sections.section_name from sections
    join section_versions on (section_versions.id = sections.version_id)
    where section_versions.version_name = 'version A'
  )
  
  UNION
  
  select * from sections
  join section_versions on (section_versions.id = sections.version_id)
  where section_versions.version_name = 'version A'
  ;
  </code></pre>
  
  <p><strong>This is probably a naive try, so I am looking for a better solution.</strong></p>
  
  <p>It would be nice to have one query that will handle:</p>
  
  <ol>
  <li>Selecting only "default"</li>
  <li>Selecting a specific version</li>
  <li>Working when no default version exists (f.i. like Instruments)</li>
  </ol>