
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select Every Alternative Row and Display in Descending Order in SQL
To fetch every alternative row, use MOD() under WHERE. Then use ORDER BY DESC to display the result in descending order −
select *from yourTableName where mod(yourColumnName,2)=1 order by yourColumnName DESC;
Let us first create a table −
mysql> create table DemoTable ( UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientName varchar(40), ClientAge int ); Query OK, 0 rows affected (1.02 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(ClientName,ClientAge) values('Chris',34); Query OK, 1 row affected (0.47 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('Tom',45); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('Sam',36); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('Carol',42); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable(ClientName,ClientAge) values('David',38); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+------------+-----------+ | UniqueId | ClientName | ClientAge | +----------+------------+-----------+ | 1 | Chris | 34 | | 2 | Tom | 45 | | 3 | Sam | 36 | | 4 | Carol | 42 | | 5 | David | 38 | +----------+------------+-----------+ 5 rows in set (0.00 sec)
Let us now select every alternative row and display in descending order −
mysql> select *from DemoTable where mod(UniqueId,2)=1 order by UniqueId DESC;
This will produce the following output −
+----------+------------+-----------+ | UniqueId | ClientName | ClientAge | +----------+------------+-----------+ | 5 | David | 38 | | 3 | Sam | 36 | | 1 | Chris | 34 | +----------+------------+-----------+ 3 rows in set (0.00 sec)
Advertisements