0

Please help, need to select from table 1, but if entry with the same id exists in table2 should return name and last name from there otherwise values from table1

table1

id|name|lastname

1 |    |
2 |    |
3 |    |

table2

id|name|lastname
3 |    |

Tried this, but not working

SELECT ID, NAME, LASTNAME
    FROM table1 
    WHERE EXISTS
        (SELECT 1 FROM table2 WHERE table2.ID = table1.ID)
1
  • It looks like name and lastname are null in both tables so I'm not sure what the lookup will achieve. What is "not working"? Commented May 19, 2021 at 22:10

1 Answer 1

1

if entry with the same id exists in table2 should return name and last name from there otherwise values from table1

You want a LEFT OUTER JOIN and then to use COALESCE:

SELECT t1.id,
       COALESCE( t2.name, t1.name ) AS name,
       COALESCE( t2.lastname, t1.lastname ) AS last_name
FROM   table1 t1
       LEFT OUTER JOIN table2 t2
       ON ( t1.id = t2.id )

Which, for your sample data:

CREATE TABLE table1 ( id, name, lastname ) AS
SELECT 1, 'Alice1', 'Abbot1' FROM DUAL UNION ALL
SELECT 2, 'Betty1', 'Baron1' FROM DUAL UNION ALL
SELECT 3, 'Carol1', 'Casey1' FROM DUAL;

CREATE TABLE table2 ( id, name, lastname ) AS
SELECT 3, 'Carol2', 'Casey2' FROM DUAL;

Outputs:

ID NAME LAST_NAME
3 Carol2 Casey2
2 Betty1 Baron1
1 Alice1 Abbot1

db<>fiddle here

Sign up to request clarification or add additional context in comments.

1 Comment

Thats exactly what i need mate, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.