I'm trying to create a table with a compound primary key where the second column is ordered descending:
CREATE TABLE AccountHistory (
AccountNumber BIGINT NOT NULL,
Ts TIMESTAMP NOT NULL,
Memo TEXT,
ChangeAmount BIGINT NOT NULL,
PRIMARY KEY (AccountNumber, ts DESC)
);
However, PostgreSQL is saying there's a syntax error at the DESC
clause.
The ORDER BY command sorts the result set in ascending order by default. To sort the records in descending order, use the DESC keyword.
Each expression can be followed by an optional ASC or DESC keyword to set the sort direction to ascending or descending. ASC order is the default.
The ASC keyword helps us sort in ascending order while the DESC sorts in descending order. If no keyword is specified in which we have to sort the records in the column, it will take its default value.
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.
If you want to sort some of the data in ascending order and other data in descending order, then you would have to use the ASC and DESC keywords. SELECT * FROM table ORDER BY column1 ASC, column2 DESC; That is how to use the ORDER BY clause in SQL to sort data in ascending order.
I think it would be reasonable to do that, as semantically an index in ascending or descending order is the same, but PostgreSQL does not support it. There's no way to control the index order of an index that is auto-created to back a primary key.
PostgreSQL won't let you create one by creating the index manually as a UNIQUE
index with DESC
sorting order then creating a declared PRIMARY KEY
constraint with it using ALTER TABLE ... ADD CONSTRAINT ... PRIMARY KEY USING INDEX ...
. It will fail with:
ERROR: index "foopk" does not have default sorting behavior
I do not know off the top of my head why Pg requires this. Searching the source code for the above error would probably find you a suitable comment.
You can get PRIMARY KEY
-like behaviour without the constraint metadata just by creating the unique index separately. That might be OK for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With