From: Laurenz Albe <laurenz.albe@cybertec.at>
To: Philipp Kraus <philipp.kraus@tu-clausthal.de>
To: pgsql-general@postgresql.org <pgsql-general@postgresql.org>
Subject: Re: sql function with empty row
Date: Thu, 17 May 2018 06:32:15 +0200
Message-ID: <1526531535.2430.3.camel@cybertec.at> (raw)
In-Reply-To: <A5624A8E-1E70-49BC-9CBB-798AE6F8276F@tu-clausthal.de>
References: <A5624A8E-1E70-49BC-9CBB-798AE6F8276F@tu-clausthal.de>
Philipp Kraus wrote:
> I have defined a SQL function
>
> CREATE OR REPLACE FUNCTION substancetrivialname(text)
> RETURNS substance
> LANGUAGE 'sql'
> COST 100
> VOLATILE
> AS $BODY$
> select s.* from substancetrivialname n
> join substance s on s.id = n.idsubstance
> where lower(btrim(n.name)) = lower(btrim($1));
> $BODY$;
>
> substance and substancetrivialname have got a 1-to-N relationship (for each substance can exist multiple trivial names).
> If I call the function with a non-existing trivial name it returns a single row with all fields are set to NULL.
>
> If I run the join query directly it returns an empty record set on a non-existing trivial name.
> I expected equal behavior on my function, so my question is, how can I fix this?
The difference is that the function has to return exactly one value,
while the query it at liberty to return 0, 1 or more rows.
Since there is no result, it returns a NULL value.
What you are seeing is a valid composite NULL value:
SELECT ROW(NULL, NULL) IS NULL;
?column?
----------
t
(1 row)
It looks weird, but the SQL standard wants it that way.
NULLs and composite types is a topic that can really twist your brain.
Yours,
Laurenz Albe
--
Cybertec | https://www.cybertec-postgresql.com
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: laurenz.albe@cybertec.at, philipp.kraus@tu-clausthal.de
Subject: Re: sql function with empty row
In-Reply-To: <1526531535.2430.3.camel@cybertec.at>
References: <A5624A8E-1E70-49BC-9CBB-798AE6F8276F@tu-clausthal.de> <1526531535.2430.3.camel@cybertec.at>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox