tags:

views:

181

answers:

2

I'm learning how to use sqlite3 with python. The example in the text book I am following is a database where each Country record has a Region, Country, and Population.

The book says:

The following snippet uses the CONSTRAINT keyword to specify that no two entries in the table being created will ever have the same values for 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 remove it, the PRIMARY KEY statement alone seems to ensure that each country has a unique name for that region.

+3  A: 

Country_key is simply giving a name to the constraint. If you do not do this the name will be generated for you. This is useful when there are several constraints on the table and you need to drop one of them.

As an example for dropping the constraint:

ALTER TABLE PopByCountry DROP CONSTRAINT Country_Key
Matthew Jones
That's correct. The actual PRIMARY KEY constraint is no different with or without the CONSTRAINT keyword. The keyword simply allows us to identify the constraint.
Matthew Jones
Thanks for the really quick reply. I'll mark this as the answer if you could give me a simple example of command to edit/drop the constraint later on.
sql beginner
Turns out I misspoke earlier. You can only drop constraints, not edit them directly. However, you could drop one and add another (in effect making an edit)
Matthew Jones
It turns out that sqlite does not support DROP CONSTRAINT, but I'll keep it in mind for when I use a different SQL Engine.
sql beginner
+1  A: 

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

By specifically putting CONSTRAINT in the query you are essentially specifying a name for your primary key constraint.

Miky Dinescu