Search code examples
pythonsqlpostgresqlpsql

Python code check for duplicate psql rows with a null value, None in python


I have something strange in my opinion. I try with a postgresql function to check for existing rows in a postgresql database. These rows hold also Null-values. These are created with a psql stored procedure: i read an excel-file with the help of pandas, when a cell-value in excel is empty then pandas stores this value as a 'nan'-value. To store this value in psql-datase i change the value to a python None-value

According to this site python None is equal to PSQL Null:

[https://www.psycopg.org/docs/usage.html#passing-parameters-to-sql-queries][1]

( The most common method to check for NaN values is to check if the variable is equal to itself. If it is not, then it must be NaN value.):

if tegenrekening!=tegenrekening: 
            tegenrekening = None

I read the database and the value in psql is indeed Null. So this is working in my opinion.

But strange thing is when i later on check if this row with Null-value exists in the database the database quotes it does not exist?! I use this to check if the row exists:

CREATE OR REPLACE FUNCTION public.control2(_datum date, 
_tegenrekening character varying)
 RETURNS TABLE(bestaat boolean)
 LANGUAGE sql
AS $function$
BEGIN
    RETURN QUERY
    SELECT EXISTS (SELECT 1 FROM "rekening" WHERE "DATUM"=_datum
    AND "TEGENREKENING"=_tegenrekening) as bestaat
LIMIT 1;
END
$function$

When i run the psql-function in python the function prints "False" meaning the row doesn't exist. When i print the values in python which are passed to the function, variable 'tegenrekening' gives 'None'.

So when checking for psql Null with python None it doesn't work? So it is not completly the same? Than how to check for a Null value in the database with a python code?

Thnx in advanced....


Solution

  • This did the job:

    if tegenrekening!=tegenrekening: 
            tegenrekening = ""
    

    So inserting "" with python inserts a Null value in psql. Not None.