2

I have the following logical condition:

WHERE (m.idAgent = agent OR agent is null)

It returns me all agents if I pass NULL as the agent param.

But how can I achieve the same thing in MYSQL?

That is, if I pass NULL for agent then the rest of that part of the WHERE condition (m.idAgent = agent) should be ignored and only the other conditions, not shown, which are not NULL should be considered.

2
  • Is that not a MySQL condition? It's exactly what you need. Commented Aug 12, 2019 at 10:49
  • @Nick i want a query where if my condition parameter is null then that part of the where condition should be ignored and rest of the not null parameter should be considered. Commented Aug 12, 2019 at 11:16

2 Answers 2

2

You could use COALESCE as follows:

WHERE COALESCE(agent, m.idAgent) = m.idAgent

This should work because when agent is NULL, it would just be replaced with the RHS of the comparison, and therefore would always pass. I presume that the following is actually what your code looks like:

WHERE COALESCE(?, m.idAgent) = m.idAgent

Here the ? is a placeholder for a value to be bound in the statement.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the IF() function:

WHERE IF(agent IS NULL, TRUE, m.idAgent = agent)

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.