Postgresql – Can you create an index in the CREATE TABLE definition

postgresql

I want to add indexes to some of the columns in a table on creation. Is there are way to add them to the CREATE TABLE definition or do I have to add them afterward with another query?

CREATE INDEX reply_user_id ON reply USING btree (user_id);

Best Solution

There doesn't seem to be any way of specifying an index in the CREATE TABLE syntax. PostgreSQL does however create an index for unique constraints and primary keys by default, as described in this note:

PostgreSQL automatically creates an index for each unique constraint and primary key constraint to enforce uniqueness.

Other than that, if you want a non-unique index, you will need to create it yourself in a separate CREATE INDEX query.