http://www.depesz.com/2012/06/10/why-is-upsert-so-complicated/ is an importand read for postgresql.