How to Filter Data within Date Range with Searched Data?

Viewed 62

I have fetched data within date range.

query = "SELECT * FROM table WHERE (date BETWEEN '2020-01-01' AND '2020-12-31')";

Its working well shows data between dates but when I search perticular data within date range it is showing all matched records outside date range.

query = "SELECT * FROM table WHERE (date BETWEEN '2020-01-01' AND '2020-12-31') AND ID LIKE '%dhaval%' OR firstname LIKE '%dhaval%' OR lastname LIKE '%dhaval%' ";

Above query searches all data named dhaval in entire table.

I want searched data within date range how can I do this ?

2 Answers

You have parentheses in your condition, but in the wrong place. You would seem to want:

WHERE date BETWEEN '2020-01-01' AND '2020-12-31' AND
      (ID LIKE '%dhaval%' OR firstname LIKE '%dhaval%' OR lastname LIKE '%dhaval%')

You need to learn about AND and OR and the precedence of operations. They work in a manner similar to arithmetic operators. So, 1 + 2 * 3 is 6 and not 9, because it is parsed as 1 + (2*3). In SQL Statements, OR is like + and AND is like *.

You must know how to use brackets. 1st part is before AND and 2nd is after

query = "SELECT * FROM table WHERE (date BETWEEN '2020-01-01' AND '2020-12-31') 
      AND (ID LIKE '%dhaval%' OR firstname LIKE '%dhaval%' OR lastname LIKE '%dhaval%') ";
Related