Skip to content
Advertisement

How to only display current and valid data from 2 tables in sql

I have these two tables:

Table imp_source:

Product     class       seq
  5           5          1
  5           3          2
  5           16         3
  8           1          1
  8           4          2

Table imp_update:

Product     class       seq
  5           6          4
  8           1          6
  8           4          2
  8           23         3
  9           3          1

I need to write a query to have this result:

Product     class       seq
  5           5          1
  5           3          2
  5           16         3
  5           6          4
  8           1          6
  8           4          2
  8           23         3
  9           3          1
  • All values of imp_update
  • The values of imp_source when there is no update for seq column of a product/class combination.

Update 1:

As you can see, the row in imp_source is not in result

  product  class    seq    
    8       1       1

Because in imp_update the seq column of product/class combination is updated:

product   class    seq
    8       1       6

Advertisement

Answer

We can use a union approach here with the help of exists logic:

SELECT s.Product, s.class, s.seq
FROM imp_source s
WHERE NOT EXISTS (SELECT 1 FROM imp_update u
                  WHERE u.Product = s.Product AND u.class = s.class)
UNION ALL
SELECT Product, class, seq
FROM imp_update
ORDER BY Product;

screen capture from demo link above

Demo

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement