63

Can the following query be modified to return all records if the ? is null?

SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = ?;
0

4 Answers 4

93

Try this:

SELECT * 
FROM MY_TABLE 
WHERE @parameter IS NULL OR NAME = @parameter;
Sign up to request clarification or add additional context in comments.

5 Comments

How to use this in PHP ?
@prograshid - Just execute the query in PHP
I tried to exucute query string but its giving when accessing the result. Saying undefined function call fetch_assoc
@prograshid This has nothing to do with MySQL, you have a problem in your php code. Just ask a new question here about it.
If you happen to have other predicates (something) I would add parentheses to ensure the evaluation order is what you intend [see stackoverflow.com/questions/1241142/… ] for example: WHERE something AND (@parameter IS NULL OR NAME=@parameter)
46

You can also use functions IFNULL,COALESCE,NVL,ISNULL to check null value. It depends on your RDBMS.

MySQL:

SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = IFNULL(?,NAME);

or

SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = COALESCE(?,NAME);

ORACLE:

SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = NVL(?,NAME);

SQL Server / SYBASE:

SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = ISNULL(?,NAME);

2 Comments

This won't work if there are nulls in NAME. But for non-nullable columns this is the way to go =) (EDIT: at least not in SQL Server)
Beware that this can produce slower queries than conditioning the SQL to not contain the where clause when the parameter is null.
2

The foll. query will handle the case where the Name (table column value) can also be NULL:

SELECT NAME, SURNAME FROM MY_TABLE WHERE COALESCE(NAME,'') = COALESCE(?,NAME,'');

Comments

0
SELECT NAME
FROM MY_TABLE
WHERE NAME LIKE CASE WHEN ? IS NOT NULL THEN ? ELSE '%' END

This will work perfectly but it will return only the not null values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.