Sobes.tech
Junior — Middle

How to formulate an SQL query that imposes a restriction on an existing table?

sobes.tech AI

Answer from AI

To add a constraint to an existing table in SQL, the command ALTER TABLE with the subcommand ADD CONSTRAINT is used. For example, to add a uniqueness constraint on the email column in the users table:

ALTER TABLE users
ADD CONSTRAINT unique_email UNIQUE (email);

Other examples of constraints that can be added include:

  • PRIMARY KEY — defines the primary key
  • FOREIGN KEY — defines a foreign key
  • CHECK — sets a condition for values

It is important that the data in the table complies with the new constraint, otherwise the command will result in an error.