Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql Merging Rows

Given Table A and Table B below, could someone please guide me to what SQL/PLPGSQL I should use to produce the required result. Many thanks.

TABLE A

+--------+-------+-------+
| USR_ID | COL1  | COL2  |
+--------+-------+-------+
|    1   |       |  101  |
+--------+-------+-------+
|    2   |       |  101  |
+--------+-------+-------+

TABLE B

+--------+-------+-------+
| USR_ID | COL1  | COL2  |
+--------+-------+-------+
|    1   |  103  |       |
+--------+-------+-------+
|    3   |  102  |       |
+--------+-------+-------+

REQUIRED RESULT

+--------+-------+-------+
| USR_ID | COL1  | COL2  |
+--------+-------+-------+
|    1   |  103  |  101  |
+--------+-------+-------+
|    2   |       |  101  |
+--------+-------+-------+
|    3   |  102  |       |
+--------+-------+-------+
like image 390
Adev Avatar asked Dec 11 '25 21:12

Adev


1 Answers

use coalesce to give non-null values precedence

select coalesce(a.usr_id,b.usr_id) usr_id,
coalesce(a.col1,b.col1) col1,
coalesce(a.col2,b.col2) col2
from tablea a full join tableb b
on a.usr_id = b.usr_id
like image 52
FuzzyTree Avatar answered Dec 14 '25 16:12

FuzzyTree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!