Why does comparing types in MySQL won’t raise an error?

MySQLMySQLi Database

If you try to compare string to int, MySQL won’t raise an error because it converts string to int. Let us first create a table −

mysql> create table DemoTable1852
     (
     Value1 varchar(20),
     Value2 int
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1852 values('1John',1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1852 values('John',1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1852 values('1',1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1852 values('John1',1);
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1852;

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
| 1John  |      1 |
| John   |      1 |
| 1      |      1 |
| John1  |      1 |
+--------+--------+
4 rows in set (0.00 sec)

Here is the query to compare types in MySQL and it won’t raise an error −

mysql> select Value1,Value2, Value1=Value2 as Result from DemoTable1852;

This will produce the following output −

+--------+--------+--------+
| Value1 | Value2 | Result |
+--------+--------+--------+
| 1John  |      1 |      1 |
| John   |      1 |      0 |
| 1      |      1 |      1 |
| John1  |      1 |      0 |
+--------+--------+--------+
4 rows in set, 3 warnings (0.00 sec)
raja
Published on 26-Dec-2019 11:00:23
Advertisements