Umesh Kacha
Umesh Kacha

Reputation: 13686

Java SQL resultset retrieval order is not correct

I have the following three row in my table say tb1

key   time   id   rowid
X     11:40  1      1
Y     4:50   1      2
Z     6:48   1      2 

Now I am using JDBC to get records and iterating over resultset as shown below:

rs = statement.executeQuery("select * from tb1")
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
while(rs.next())
{
   for(int i = 1; i <= cols ; i++)
   {
     System.out.println("col name " + md.getColumnName(i));
     System.out.println("col name " + rs.getObject(i));
   }

}

When I execute the above code strangely it always prints second row first and then first row and then third row. In short resultset data retrieval is not in order. Why is this?

Upvotes: 1

Views: 3601

Answers (1)

rgettman
rgettman

Reputation: 178293

You have not specified an "order by" clause. In general, databases are not required to return rows in any order unless an "order by" clause is specified. Add an order by clause to your select statement.

Upvotes: 4

Related Questions