Our Java program is fetching data randomly from postgreSQL. how can it be resolved? What should be done in order to get data in a sequential order?
We have a table named grocery in our postgresql, which has entries from 0 to 99. the java code is fetching this entire table but in a random order.
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost/test", "postgres",
"manafara");
connection.setAutoCommit(false);
Statement st = connection.createStatement();
String sql = "Select * from grocery";
ResultSet rs = st.executeQuery(sql);
Statement st1 = connection.createStatement();
ResultSet rs1 = st1.executeQuery("Select COUNT(*) AS TOTAL from grocery");
int n = 0;
while (rs1.next()) {
n = rs1.getInt("TOTAL");
}
System.out.println("Count: " + n);
int a = 0;
Double db[][] = new Double[n][2];
while (rs.next()) {
db[a][0] = (double) rs.getInt(4);
db[a][1] = rs.getDouble(6);
a++;
}
1 Answer 1
Quoting documentation:
If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce.
This effectively means that without ORDER BY
there is no guarantee at all that rows will be fetched in the same order from one execution to another.
If you need to get rows in the same order over and over again, you will need to add ORDER BY
clause to your query. In your case it could be something like:
select * from grocery order by id
Values of column id
have to be unique in order to guarantee same order of rows when fetching data.
order by
so the database is free to choose any order it likes. Rows in a relational database are NOT sorted.