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.
A CONSTRAINT clause is an optional part of a CREATE TABLE statement or ALTER TABLE statement. A constraint is a rule to which data must conform. Constraint names are optional. A CONSTRAINT can be one of the following: a column-level constraint.
Other constraints (primary key, foreign key, unique, check, and default) can be removed using an ALTER TABLE DROP CONSTRAINT statement. For such statements, a constraint name has to be specified.
Some CONSTRAINTS can be used along with the SQL CREATE TABLE statement. The general structure of the SQL CONSTRAINT is defined as: The CONSTRAINT keyword is followed by a constraint name followed by a column or a list of columns.
We can specify constraints at the time of creating the table using CREATE TABLE statement. We can also specify the constraints after creating a table using ALTER TABLE statement. Syntax: Below is the syntax to create constraints using CREATE TABLE statement at the time of creating the table.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With