PostgreSQL: Can you create an index in the CREATE TABLE definition?

前端 未结 3 729
既然无缘
既然无缘 2020-12-24 00:11

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 anot

3条回答
  •  -上瘾入骨i
    2020-12-24 00:39

    Peter Krauss is looking for a canonical answer:

    There are a MODERN SYNTAX (year 2020), so please explain and show examples, compatible with postgresql.org/docs/current/sql-createtable.html

    You are searching for inline index definition, which is not available for PostgreSQL up to current version 12. Except UNIQUE/PRIMARY KEY constraint, that creates underlying index for you.

    CREATE TABLE

    [ CONSTRAINT constraint_name ] { CHECK ( expression ) [ NO INHERIT ] | UNIQUE ( column_name [, ... ] ) index_parameters | PRIMARY KEY ( column_name [, ... ] ) index_parameters |


    The sample syntax of inline column definition(here SQL Server):

    CREATE TABLE tab(
      id INT PRIMARY KEY,                            -- constraint
      c INT INDEX filtered (c) WHERE c > 10,         -- filtered index
      b VARCHAR(10) NOT NULL INDEX idx_tab_b,        -- index on column
      d VARCHAR(20) NOT NULL,
      INDEX my_index NONCLUSTERED(d)                 -- index on column as separate entry
    );
    

    db<>fiddle demo

    The rationale behind introducing them is quite interesting What are Inline Indexes? by Phil Factor

提交回复
热议问题