Home sql What does CONSTRAINT mean in this context?

What does CONSTRAINT mean in this context?

Author

Date

Category

There are 2 tables:

CREATE TABLE company (
  id integer NOT NULL,
  name character varying,
  CONSTRAINT company_pkey PRIMARY KEY (id)
);
CREATE TABLE person (
  id integer NOT NULL,
  name character varying,
  company_id integer,
  CONSTRAINT person_pkey PRIMARY KEY (id)
);

The script was not written by me, and I am trying to understand the logic of the person who did it. What might be the point of this constraint CONSTRAINT person_pkey PRIMARY KEY (id) ? And in the second case, it is the same. Is it a limitation that id can only be the primary key? Why might this be necessary? All the more so to name this limitation. Please help me figure out why to make such a CONSTRAINT ?


Answer 1, authority 100%

Definition

CONSTRAINT company_pkey PRIMARY KEY (id)

is equivalent to definition

PRIMARY KEY (id)

means that id is the primary key of the table.

Because in this case, the primary key consists of one column, then it could be specified at the field level:

CREATE TABLE company (
  id integer PRIMARY KEY,
  name character varying
);

The ability to define a key at the table level is useful if the key is composite

PRIMARY KEY (id, name)

In the first case, the constraint has a name. This name will be displayed in error messages. You can also remove this restriction by name. If the name of the constraint is not specified explicitly, it will be generated by the DBMS.

It says in the documentation :

CONSTRAINT constraint_name
An optional name for a column or table constraint. If the constraint is violated, the constraint name is present in error messages, so constraint names like col must be positive can be used to communicate helpful constraint information to client applications. (Double-quotes are needed to specify constraint names that contain spaces.) If a constraint name is not specified, the system generates a name.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions