MySQL query to find alternative records from a table

MySQLMySQLi Database

To find alternative records from a table, you need to use the OR condition as in the below syntax −

select *from yourTableName where yourColumnName=yourValue1 OR yourColumnName=yourValue2…...N;

Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable772(Name,Age) values('Chris',21);
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable772(Name,Age) values('Robert',26);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable772(Name,Age) values('Mike',27);
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable772(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.45 sec)
mysql> insert into DemoTable772(Name,Age) values('Carol',28);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable772(Name,Age) values('David',25);
Query OK, 1 row affected (0.93 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable772;

This will produce the following output -

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

Here is the query for MySQL OR −

mysql> select *from DemoTable772 where Id=2 OR Id=4 OR Id=6;

This will produce the following output -

+----+--------+------+
| Id | Name   | Age  |
+----+--------+------+
|  2 | Robert | 26   |
|  4 | Sam    | 24   |
|  6 | David  | 25   |
+----+--------+------+
3 rows in set (0.01 sec)
raja
Published on 03-Sep-2019 08:54:45
Advertisements