Share on Google+Share on Google+

JDBC: Sorting Table Example

In this section, you will learn how to sort your table records under any column using JDBC API.

JDBC: Sorting Table Example

In this section, you will learn how to sort your table records under any column using JDBC API.

ORDER BY Clause :

You can sort your table record either in ascending order or in descending order according to any field by using ORDER BY Clause.  It manages your table records in sorted order of specified column.
When You write only 'ORDER BY column_name' , by default it returns records sorted in ascending order. You can also use "asc" for ascending order.
For descending order use 'desc'  as 'ORDER BY column_name desc'

Example :  In this example we are arranging student records in descending order of roll_no .

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class SortingRecords{
	public static void main(String[] args){
		System.out.println("Sorting rocords of table in JDBC...");
		Connection con = null;
		Statement statement = null;
		ResultSet rs = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "students";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {

			// Connecting to the database
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {
				statement = con.createStatement();

				// Using ORDER BY Clause 
				String sql = "SELECT * FROM student ORDER BY roll_no desc";
				rs = statement.executeQuery(sql);
				while ( {
					int roll = rs.getInt("roll_no");
					String name = rs.getString("name");
					String course = rs.getString("course");
					System.out.println(roll + "\t" + name + "\t" + course);


			} catch (SQLException e) {
		} catch (Exception e) {

Output :

Sorting rocords of table in JDBC...
RollNo	Name	Course
4	Andru	MCA
3	Rose	MCA
2	Mandy	BCA
1	Ron	MCA



Posted on: September 26, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null