Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does sql = FALSE always return true

Tags:

sql

mysql

No matter what I do in MySQL 5.0 such as

SELECT 'test' = FALSE

SELECT '' = FALSE

I always get a 1 back in SQL. What is the reason for that? I was expecting a 0 or FALSE

EDIT adding context to the questions. This is how the problem came about, it happened that $name inadvertently became false making this join always pass, then I wondered why this works.

SELECT a.id
FROM user a 
INNER JOIN inventory b ON b.user_id = a.id AND b.name = $name
like image 686
user391986 Avatar asked Apr 10 '13 22:04

user391986


People also ask

What does false mean in SQL?

It is a where condition to be used when the query should not return any result. Some DBMS supporting boolean values, Postgres for example, are used to work with that instead of the classic where 1=1 . Basically then, where false is the same of where 1=0 .

Can a SQL query return a Boolean?

Details of sql differ. SQL Server does not support a Boolean type e.g. SELECT WHEN CAST(1 AS BIT) THEN 'YES' END AS result -- results in an error i.e. CAST(1 AS BIT) is not the same logical TRUE.

How display True or False in SQL?

SQL Server does not have the Boolean data type. There are no built-in values true and false . One alternative is to use strings 'true' and 'false' , but these are strings just like any other string. Often the bit type is used instead of Boolean as it can only have values 1 and 0 .

When exists return false in SQL?

If EXISTS (subquery) returns at least 1 row, the result is TRUE. If EXISTS (subquery) returns no rows, the result is FALSE. If NOT EXISTS (subquery) returns at least 1 row, the result is FALSE.


2 Answers

In MySql FALSE is a constant literal which is always evaluated as 0.

So you are checking if 'test' = 0 or if '' = 0, and since you are comparing a string with an integer, MySql will try to cast the string to an integer.

If you try this query:

SELECT 'test' = FALSE

it will return 1 (TRUE) because 'test' will be converted to 0, while if you try this:

SELECT '1test' = FALSE

it will return 0 (FALSE) because '1test' will be converted to 1.

like image 102
fthiella Avatar answered Oct 10 '22 16:10

fthiella


This has to do with MySQL's implicit conversion when using comparison operators (i.e. =)

Taken from the docs:

Strings are automatically converted to numbers and numbers to strings as necessary.

So, in your case:

  • 'test' gets converted to 0
  • FALSE is 0
  • 0 = 0 is TRUE.
like image 42
Jason McCreary Avatar answered Oct 10 '22 18:10

Jason McCreary