I have two tables that have identical columns. I would like to join these two tables together into a third one that contains all the rows from the first one and from the sec
UNION simply doesn't do what you describe. This query should:
CREATE TABLE AS
SELECT date, location_code, product_code, quantity
FROM transactions_kitchen k
UNION ALL
SELECT h.date, h.location_code, h.product_code, h.quantity
FROM transactions_admin h
LEFT JOIN transactions_kitchen k USING (location_code, date)
WHERE k.location_code IS NULL;
LEFT JOIN / IS NULL to exclude rows from the second table for the same location and date. See:
Use CREATE TABLE AS instead of SELECT INTO. The manual:
CREATE TABLE ASis functionally similar toSELECT INTO.CREATE TABLE ASis the recommended syntax, since this form ofSELECT INTOis not available in ECPG or PL/pgSQL, because they interpret theINTOclause differently. Furthermore,CREATE TABLE ASoffers a superset of the functionality provided bySELECT INTO.
Or, if the target table already exists:
INSERT INTO transactions_combined ()
SELECT ...
Aside: I would not use date as column name. It's a reserved word in every SQL standard and a function and data type name in Postgres.