Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data type of $1 vs. coalesce($1)

This statement doesn't work with PostgreSQL 8.2.4 and PHP 5.2.17:

 pg_query_params('SELECT $1', array(1));
 ERROR: could not determine data type of parameter $1 

Fair enough. This is a possible fix:

 pg_query_params('SELECT CAST($1 AS INTEGER)', array(1));

That makes sense since we're being explicit about the data type.

But the following statement also works, although it should be equivalent to the first expression:

 pg_query_params('SELECT COALESCE($1)', array(1));

Why? Does COALESCE somehow modify the data type of $1, or guarantee some simple data type as the result?

Edit: The docs are rather short on the subject of COALESCE.

like image 578
l0b0 Avatar asked Aug 24 '11 09:08

l0b0


1 Answers

coalesce always return the first non-null string,
in the event of all null (in your case, is undefined variable of $1) supplied,
it lead to NULL.

NULL is not truly same as undefined

pardon my bad explanation ...

The first example, you are trying to return a undefined variable which lead to an error.

However, in the third example, you are trying to return a NULL value (returned by coalesce),
there is no more undefined variable, just a NULL returned, this make select work fine

like image 173
ajreal Avatar answered Nov 04 '22 01:11

ajreal