-1

I have to write a query where the where clause should work on only if the field value is not empty else all record should be fetched.

I have a table name post

id    | valid_month | name |
------+-------------+------|
  1   | 1,2,3       | post1|
  2   | 1,2         | post2|
  3   |             | post3|
  4   | 2,5         | post4|
  5   |             | post5|
  ----+-------------+------+

I want query like

select * from post where IF(valid_month != "") THEN valid_month REGEXP '[[:<:]]3[[:>:]]' END IF;

and result should like

id    | valid_month | name |
------+-------------+------|
  1   | 1,2,3       | post1|
  3   |             | post3|
  5   |             | post5|
  ----+-------------+------+

Is there any way to get this output in MySQL?

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

1

You could gain this behavior with the logical or operator:

SELECT *
FROM   post
WHERE  valid_month = '' OR valid_month REGEXP '[[:<:]]3[[:>:]]';
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You can use the CASE as well

SELECT *
FROM   post
WHERE (
       CASE WHEN IFNULL(valid_month,'') != '' THEN 
           valid_month REGEXP '[[:<:]]3[[:>:]]' 
       ELSE 1 = 1 
      END);
Vidhyut Pandya
  • 1,605
  • 1
  • 14
  • 27