Latest |Kites |Pictures |Programming |Life
[filed under Programming]MySQL compare sub query null

Hey, this is cool. I had a query like so:

SELECT stuff
FROM table
WHERE
col = ( SELECT col FROM table_2 WHERE id IN (1,2,3) )

And the sub query was returning NULL sometimes. So I wanted the rows from table where col is null. But the syntax to do that would be:

SELECT stuff
FROM table
WHERE
col IS ( SELECT col FROM table_2 WHERE id IN (1,2,3) )

Now this query isn't going to work when the sub query returns a number. The answer is to use this funky operator thatsolves this problem <=>, the null safe equality operator:

SELECT stuff
FROM table
WHERE
col <=> ( SELECT col FROM table_2 WHERE id IN (1,2,3) )

Smooth :-)

28th of October, 2008@12:00:28 PM
8 comments, permanent link to article

Comments

[30th of Oct, 2008 @ 10:45 AM]
Joe said:
Nice, don't think SQL Server has this kind of operator, I would just use the ISNULL function with a value I know won't appear in table_2.

SELECT stuff
FROM table
WHERE
ISNULL(col, -1) = ISNULL(( SELECT col FROM table_2 WHERE id IN (1,2,3) ), -1)
[5th of Dec, 2008 @ 11:50 PM]
Dan said:
I do not know if ISNULL is allowed in oracle? Do you have idea?
[8th of Dec, 2008 @ 01:14 PM]
Joe said:
Looks like the Oracle version is NVL, Google is your friend:

http://cf-bill.blogspot.com/2005/10/oracle-nvl-microsoft-isnull.html
[25th of Dec, 2008 @ 08:35 AM]
Thanks Joe for link! I am Just like Dan needed to do that for Oracle, thanks for giving us the link!

Thanks
[30th of Dec, 2008 @ 12:57 AM]
hgh said:
Thanks Joe, I guess should help Dan:
http://download.oracle.com/docs/cd/B19306_01/win.102/b14308/cpp00271.htm

Thanks
HGH
[21st of Mar, 2009 @ 01:38 AM]
fatcow said:
ISNULL is not working for me ! I used fatcow database server?

Any idea?
[22nd of Mar, 2009 @ 02:09 PM]
vini said:
This cool huh.. So we select more specified field in the database. tooo smooth dude.
[16th of Oct, 2009 @ 05:12 PM]
Math said:
#

Hi,

I select the value of a table using type and I also want the mysql query to its next and previous type all this has to written in single query

select * from tb1 where type=’All calculators’,id=(all cal+1)

Is there is any option to do all this in one query.

Check this if you are a human being. Thanks. (I'm trying to reduce my comment spam :-)

Comment

Server Grind [0.0053 seconds]