Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres ON CONFLICT DO UPDATE only non null values in python

I have a table for which when processing records I get either the full record, else only the columns to be updated.

I want to write a query to handle updates but only update the columns with non null values. For example,

Existing table:

1 | John Doe | USA
2 | Jane Doe | UK

Incoming records:

(3, Kate Bill, Canada)
(2, null, USA)

I want to insert the first record and on conflict of key on second record ONLY update the last column.

I'm not sure how to write this using a execute_values method call:

execute_values(cursor, "INSERT INTO user_data\
           (id, name, country) VALUES %s ON CONFLICT DO UPDATE SET \
            <how to only set non null values here>", vendor_records)

I'm using psycopg2 to execute this.

like image 703
ayushgp Avatar asked Apr 29 '20 05:04

ayushgp


People also ask

IS NOT NULL in if condition in PostgreSQL?

Here is an example of how to use the PostgreSQL IS NOT NULL condition in a SELECT statement: SELECT * FROM employees WHERE first_name IS NOT NULL; This PostgreSQL IS NOT NULL example will return all records from the employees table where the first_name does not contain a null value.

What does on conflict do PostgreSQL?

ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action.

What is the use of NOT NULL in PostgreSQL?

The not-null constraint in PostgreSQL ensures that a column can not contain any null value. This is a column constraint. No name can be defined to create a not-null constraint. This constraint is placed immediately after the data-type of a column.

Does count include null Postgres?

The COUNT(*) function returns the number of rows returned by a SELECT statement, including NULL and duplicates.


1 Answers

In the on conflict (pay particular attention to the do update set name = expression) you can use coalesce with the excluded values to update columns to the specified values (if not null), or the existing values (if specified is null); This would be that format:

-- setup  
 create table test1(id  integer primary key, col1 text,col2 text); 
 insert into test1(id, col1, col2)
    values (1, 'John Doe', 'USA')
         , (2, 'Jane Doe', 'UK');
 select * from test1; 

 -- test on conflict
 insert into test1 as t(id, col1, col2)     
      values (3, 'Kate Bill', 'Canada')
           , (2, null, 'USA')
    on conflict(id) do update   
       set col1 = coalesce(excluded.col1,  t.col1)
         , col2 = coalesce(excluded.col2,  t.col2);

-- validate
 select * from test1;     
like image 63
Belayer Avatar answered Oct 12 '22 23:10

Belayer