Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named CONSTRAINT benefits

I'm learning SQL and stumbled about CONSTRAINT. I can define them like this:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CHECK (price > 0)
);

and like this:

CREATE TABLE products (
    product_no integer,
    name text,
    price numeric CONSTRAINT positive_price CHECK (price > 0)
);

Why do I give them names? or Why I should or should not give them names? As I can see in this example and most situations in my mind I can't reuse them. So what is the benefit of giving a name to a CONSTRAINT?

like image 822
Johannes Avatar asked May 05 '11 12:05

Johannes


People also ask

What is the advantage of naming a constraint?

By naming the constraints you can differentiate violations of them. This is not only useful for admins and developers, but your program can also use the constraint names. This is much more robust than trying to parse the error message.

Should constraint names be unique?

A constraint name must be unique within the table to which it pertains.

What is a constraint name some constraints?

Constraints can be categorized into five types: A NOT NULL constraint is a rule that prevents null values from being entered into one or more columns within a table. A unique constraint (also referred to as a unique key constraint) is a rule that forbids duplicate values in one or more columns within a table.


1 Answers

There are significant benefits of giving explicit names to your constraints. Just a few examples:

  1. You can drop them by name.
  2. If you use conventions when choosing the name, then you can collect them from meta tables and process them programmatically.
like image 180
bpgergo Avatar answered Oct 09 '22 15:10

bpgergo