I have two tables which I want to connect.
+-----------+-----------+---------+
| row_id | category | val_1 |
+-----------+----------
Try an outer join.
SELECT TABLE_A.row_id, TABLE_A.category, TABLE_A.val_1, TABLE_B.val_2
FROM TABLE_B
LEFT OUTER JOIN TABLE_A ON TABLE_B.row_id = TABLE_A.row_id
ORDER BY row_id;
If you want all the results, you need an outer join, not an inner one. (Inner only returns the rows where there is a match; outer returns all rows, with the matching rows "stitched together")
This ought to do it:
SELECT
TABLE_B.row_id row_id,
TABLE_A.category category,
COALESCE(TABLE_A.val_1,1) val_1,
TABLE_B.val_2 val_2
FROM TABLE_A
RIGHT OUTER JOIN TABLE_B
ON TABLE_B.row_id = TABLE_A.row_id
ORDER BY TABLE_B.row_id;
The RIGHT OUTER JOIN
pulls all the records from Table_B even if they don't exist in Table_A, and the COALESCE statement is a function that returns its first non-NULL parameter. In this case, if there is no value in Table_A, it will return 1
, which is what your example result lists as the desired output.