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
Change UNION ALL to just UNION and it should return only unique rows from each table.
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 AS
is functionally similar toSELECT INTO
.CREATE TABLE AS
is the recommended syntax, since this form ofSELECT INTO
is not available in ECPG or PL/pgSQL, because they interpret theINTO
clause differently. Furthermore,CREATE TABLE AS
offers a superset of the functionality provided bySELECT INTO
.
Or, if the target table already exists:
INSERT INTO transactions_combined (<list names of target column here!>)
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.