Skip to content

Instantly share code, notes, and snippets.

@tlamer
Forked from anonymous/gist:4418840
Created April 2, 2014 07:43
Show Gist options
  • Select an option

  • Save tlamer/9929612 to your computer and use it in GitHub Desktop.

Select an option

Save tlamer/9929612 to your computer and use it in GitHub Desktop.
-- Structure:
-- src_customers: id, name, address
-- dim_customers: id, name, address
-- Find new records
DROP TABLE IF EXISTS tmp_new;
CREATE TABLE tmp_new AS
SELECT id FROM src_customers
EXCEPT
SELECT id FROM dim_customers;
INSERT INTO dim_customers
SELECT s.* FROM tmp_new n
JOIN src_customers s on s.id = n.id;
-- Update changed records
UPDATE dim_customers
SET name = diff.name,
address = diff.address
FROM (
SELECT s.*
FROM dim_customers d
JOIN src_customers s ON s.id = d.id
WHERE d.name != s.name
OR d.address != s.address) diff
WHERE dim_customers.id = diff.id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment