Correctly implement the AND condition in MySQL


To implement AND condition, the syntax is as follows −

select *from yourTableName where yourColumnName1 = yourValue1 AND yourColumnName2 = yourValue2;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table MySQLANDConditionDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> Age int
   -> );
Query OK, 0 rows affected (0.80 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into MySQLANDConditionDemo(Name,Age) values('Larry',23);
Query OK, 1 row affected (0.11 sec)
mysql> insert into MySQLANDConditionDemo(Name,Age) values('Mike',21);
Query OK, 1 row affected (0.17 sec)
mysql> insert into MySQLANDConditionDemo(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.17 sec)
mysql> insert into MySQLANDConditionDemo(Name,Age) values('David',26);
Query OK, 1 row affected (0.17 sec)
mysql> insert into MySQLANDConditionDemo(Name,Age) values('Carol',27);
Query OK, 1 row affected (0.11 sec)
mysql> insert into MySQLANDConditionDemo(Name,Age) values('Bob',28);
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from MySQLANDConditionDemo;

Here is the output −

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
| 1  | Larry | 23   |
| 2  | Mike  | 21   |
| 3  | Sam   | 24   |
| 4  | David | 26   |
| 5  | Carol | 27   |
| 6  | Bob   | 28   |
+----+-------+------+
6 rows in set (0.00 sec)

The following is the query for MySQL AND condition −

mysql> select *from MySQLANDConditionDemo where Name ='Mike' AND Age =21;

Here is the output −

+----+------+------+
| Id | Name | Age  |
+----+------+------+
| 2  | Mike | 21   |
+----+------+------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

53 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements