1

Let's say that I have a table that looks like the following:

CREATE TABLE products (
   product_no integer UNIQUE NOT NULL,
   name text,
   price numeric
);

Then if I insert values into the table, will postgres (or any similar DBMS) actually check through each row of the table or is an index automatically created? If there is no index, this becomes expensive really fast [O(N!)].

1 Answer 1

3

Yes and no. Postgres checks that the product_no has not already been inserted. It does so by checking an index, not the individual rows.

The unique constraint is implemented using an index, so checking for duplication is O(log n) not O(n).

Sign up to request clarification or add additional context in comments.

3 Comments

Ok. But what about on a distributed system where there are multiple computers storing many many rows of data?
@ArielA . . . Should be the same basic idea, using a distributed index -- it depends what you mean by "distributed" system. The unique index can be partitioned, for instance.
@ArielA A partitioned unique index must contain the partitioning key. If you shard across multiple databases, the same restriction does apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.