What does the CONSTRAINT keyword do in this CREATE TABLE statement

I am learning how to use sqlite3 with python. An example in the training course below is a database in which each country has a region, a country, and a population.

The book says:

The following snippet uses the CONSTRAINT keyword to indicate that no two entries in the table are ever created that will have the same value for the region and country:

>>> cur.execute(''' CREATE TABLE PopByCountry( Region TEXT NOT NULL, Country TEXT NOT NULL, Population INTEGER NOT NULL, CONSTRAINT Country_Key PRIMARY KEY (Region, Country)) ''') 

Please could you explain what CONSTRAINT Country_Key does here. If I delete it, the PRIMARY KEY expression in itself seems to guarantee that each country has a unique name for this region.

+7
python sql
source share
2 answers

Country_key simply indicates the name of the constraint. If you do not, a name will be created for you. This is useful when there are several restrictions in the table, and you need to drop one of them.

As an example, to remove a restriction:

 ALTER TABLE PopByCountry DROP CONSTRAINT Country_Key 
+9
source share

If you specify CONSTRAINT Contry_Key from the statement, the SQL server will generate a name for your PRIMARY KEY constraint for you (PRIMARY KEY is the type of constraint).

Specifically, by placing CONSTRAINT in a query, you are essentially specifying a name to restrict the primary key.

+1
source share

All Articles