is primary key automatically indexed in postgresql? [closed]

╄→гoц情女王★ 提交于 2021-01-21 12:09:51

问题


enter image description here

I have created table name as d with ID column as primary key and then just inserted records as shown in output, but after fetching all records this output still displayed same as order in which records are inserted. but output as a see now not in ordered form.


回答1:


PostgreSQL automatically creates an index for each unique constraint and primary key constraint to enforce uniqueness. Thus, it is not necessary to create an index explicitly for primary key columns. (See CREATE INDEX for more information.)

Source: Docs




回答2:


but after fetching all records this output still displayed same as order in which records are inserted

There is NO default "sort" order - even if there is an index on that column (which indeed is the case in Postgres: the primary key is supported by a unique index in the background)

Rows in a relational table are not sorted.

The only (really: the only) way to get a specific order is to use an ORDER BY

If you do not specify an ORDER BY the database is free to return the rows in any order it wants - and that order can change at any time.

The order can change because of various reasons:

  • other sessions are running the same statement
  • the table was updated
  • the execution plan changes
  • ...



回答3:


In addition to what the others have said, Postgres does not have a concept of a 'Clustered Index' like Microsoft SQL Server and other databases have. You can cluster an index, but it is a one-time operation (until you call it again) and will not maintain the clustering of rows upon edits, etc. See the docs

I was running into the same thing you were, where I half expected the rows to be returned in order of primary key (I didn't insert them out of order like you did, though). They did come back upon initial insert, but editing a record in Postgres seems to move the record to the end of the page, and the records quickly became out of order (I updated fields other than the primary key).



来源:https://stackoverflow.com/questions/42898988/is-primary-key-automatically-indexed-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!