Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE Clause only IF NOT NULL

Tags:

mysql

I need help with my SELECT.

I got a field that can be NULL and in it there is stored a foreign-key.

SELECT * FROM beerImage WHERE beerBRewID = brewID AND beerBrandID = beerID <--- this can be NULL

So if it's NULL nothing happens.

How can I check if beerID is NOT NULL so I can use "beerBrandID = beerID"?

like image 593
DenisCGN Avatar asked Aug 15 '12 14:08

DenisCGN


People also ask

Is != The same as is not null?

The only difference (besides the syntax) is, that the compiler guarantees that no user-overloaded operator is called when using is not null instead of !=

IS NOT NULL in if condition SQL?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Can WHERE clause have NULL?

Where Clause Null Value Syntax. The SQL allows for data selectivity (where clauses) with columns that have null values or the absence of a null value. The syntax is where COLUMN_NAME IS NULL or COLUMN_NAME IS NOT NULL.


2 Answers

You probably need something like this:

First example:

SELECT * FROM beerImage WHERE beerBRewID = brewID AND (beerID IS NULL OR beerBrandID = beerID)

Second Example:

SELECT * FROM beerImage WHERE beerBRewID = brewID AND beerID IS NOT NULL AND beerBrandID = beerID

The first example will allow you to show records which have beerID null along with the beers which beerBrandID is equal to beerID (both).

The second one will return exactly beers which correspond to beerBrandID (excluding NULL beerIDs).

like image 131
Rolice Avatar answered Oct 11 '22 18:10

Rolice


How about using with CASE statement in where clause like

WHERE
CASE WHEN  beer.id IS NOT NULL 
    THEN beer.brand_id = 12345
    ELSE TRUE
END
like image 35
Cataclysm Avatar answered Oct 11 '22 20:10

Cataclysm