Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL changing returned rows order

Tags:

postgresql

I have a table named categories, which contains ID(long), Name(varchar(50)), parentID(long), and shownByDefault(boolean) columns.

This table contains 554 records. All the shownByDefaultValues are 'false'.
When I execute 'select id, name from categories', pg returns me all the categories, orderer by its id.
Then I update some of the rows of the table('update categories set shownByDefault where parentId = 1'), update OK.
Then, when I try to execute the first query, which returns all the categories, they are returner with a very weird order.
I do not have problem to add 'order by', but since I am using JPA to get this values, anyone knows what the problem is or if there is a way to fix this?

like image 680
Mg. Avatar asked Dec 15 '08 19:12

Mg.


People also ask

How do I change the order of rows in SQL?

You can change the order of the rows by adding an ORDER BY clause at the end of your query, with a column name after. By default, the ordering will be in "ascending order", from lowest value to highest value. To change that to "descending order", specify DESC after the column name.

Does Postgres maintain insertion order?

The answer for this simple case is: "Yes". Rows are inserted in the provided order in the VALUES expression. And if your id column is a serial type, values from the underlying sequence will be fetched in that order.

How do I change the order of columns in PostgreSQL?

Postgres currently defines column order based on the attnum column of the pg_attribute table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.


2 Answers

That's not a problem. The order of rows returned by a SQL SELECT is undefined unless it has an ORDER BY. The order you get them is usually influenced by the order they are stored in the table and/or the indices that are used by the statement.

So depending on that order without using ORDER BY is a very, very bad idea.

If you need them in some order, simply specify that.

It is important that a table is a set of rows and not a sequence of rows.

like image 96
Joachim Sauer Avatar answered Jan 03 '23 23:01

Joachim Sauer


From the docs:

If the ORDER BY clause is specified, the returned rows are sorted in the specified order. If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce.

like image 45
Patryk Kordylewski Avatar answered Jan 03 '23 22:01

Patryk Kordylewski