Display the alternate rows from MySQL table
To display alternate records from MYSQL table, suppose we have the following records -
CREATE TABLE IF NOT EXISTS `empdata` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(25) NOT NULL,
`email` varchar(100) NOT NULL,
`phone` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `empdata` (`id`, `name`, `email`, `phone`) VALUES
(1, 'Anjali', 'anjali@example.com', 878433948),
(2, 'Priska', 'priska@example.com', 493905490),
(3, 'Abhi', 'abhi@example.com', 403022139),
(4, 'Joya', 'joya@example.com', 342345329),
(5, 'Ammy', 'ammy@example.com', 239848342),
(6, 'Lussi', 'lussi@example.com', 490290331);
These are the methods that you can use to get alternate or ODD-EVEN records from a MySQL table -
Method1 : MySQL MOD() method
MySQL MOD() method returns the remainder of a number divided by another number. So for getting alternate rows, we can divide the ID with 2 and displays only those having remainder 1.
Output of the above statement
+----+--------+--------------------+-----------+ | id | name | email | phone | +----+--------+--------------------+-----------+ | 1 | Anjali | anjali@example.com | 878433948 | | 3 | Abhi | abhi@example.com | 403022139 | | 5 | Ammy | ammy@example.com | 239848342 | +----+--------+--------------------+-----------+
The above statement returns only ODD rows. If you want to get even rows, write the statement as-
Output of the above statement
+----+--------+--------------------+-----------+ | id | name | email | phone | +----+--------+--------------------+-----------+ | 2 | Priska | priska@example.com | 493905490 | | 4 | Joya | joya@example.com | 342345329 | | 6 | Lussi | lussi@example.com | 490290331 | +----+--------+--------------------+-----------+
Method 2
We can also use the modulus operator instead of mod() method, like- the given statement returns only even rows-
Output of the above statement
+----+--------+--------------------+-----------+ | id | name | email | phone | +----+--------+--------------------+-----------+ | 2 | Priska | priska@example.com | 493905490 | | 4 | Joya | joya@example.com | 342345329 | | 6 | Lussi | lussi@example.com | 490290331 | +----+--------+--------------------+-----------+
similarly, the following statement returns only odd rows-
Output of the above statement
need an explanation for this answer? contact us directly to get an explanation for this answer+----+--------+--------------------+-----------+ | id | name | email | phone | +----+--------+--------------------+-----------+ | 1 | Anjali | anjali@example.com | 878433948 | | 3 | Abhi | abhi@example.com | 403022139 | | 5 | Ammy | ammy@example.com | 239848342 | +----+--------+--------------------+-----------+