Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query where clause [closed]

I have this line in my sql query:

WHERE client = $id
    AND (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1)

which gets more results than I am expecting. However, if I write it like this:

WHERE client = $id
    AND (isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1 and client = $id)

then it gets me the results I wanted, but this is the best way to write this? I just don't want run into any more issues with this code.

like image 215
user979331 Avatar asked Apr 23 '12 15:04

user979331


People also ask

Can you write SELECT query with WHERE condition?

The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.

Can we use 2 WHERE clause in SQL?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.

How does the WHERE clause work in SQL?

In a SQL statement, the WHERE clause specifies criteria that field values must meet for the records that contain the values to be included in the query results.

Can we use truncate with WHERE clause?

TRUNCATE cannot be executed with a WHERE clause means that all records will be removed from the TRUNCATE / statement.


1 Answers

You need one more set of () around the entire AND clause. This states that client = $id MUST be true, and either of the other conditions must also me true = isinvoiced = 0 OR the combination of isinvoiced = 1 and isrecurring = 1.

 WHERE client = $id
    AND ((isinvoiced = 0) OR (isinvoiced = 1 and isrecurring = 1))
like image 158
Michael Berkowski Avatar answered Sep 28 '22 16:09

Michael Berkowski