Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

False value in Where Clause Returns All Rows?

I have a query that looks like this:

`SELECT id, username FROM table_name WHERE username=0`

When I run this query MySQL returns all rows in table_name. Additionally, if I substitute 0 for false I get the same results. If I use null or an empty string then I get no rows returned (as expected).

The username column is varchar(50) if it makes a difference.

My question then is this:

Why does putting 0 or false in that query return all rows in the table? Is this a MySQL setting?

This worries me a little as I've been operating under the assumption that the above query would return no rows (in this particular case) and I wonder if this happening elsewhere in my application and what unintended consequences it might have.

like image 308
Jon Avatar asked May 23 '11 14:05

Jon


People also ask

Does the WHERE clause is used to filter records of table True False?

It is used with the SELECT, UPDATE and DELETE statement also; the WHERE clause is optional to be used with them. Used to filter the rows according to the given criteria. Limits the number of rows returned. Followed by a logical condition that returns either true or false.

Can we use two 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.

What does WHERE true mean in SQL?

This means that if ConditionMet(data) is true, then only return rows where AccountID matches the AcctId you are passing in. If it is false, then return all rows.


1 Answers

username is being cast to an int of 0 to make the comparsion. 0=0 evaluates to true, so it's like there's no WHERE clause at all here. You could use username='' if you're trying to get a non-null blank username.

like image 60
Dan Avatar answered Sep 21 '22 12:09

Dan