Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does keyword CONSTRAINT do in this CREATE TABLE statement

Tags:

python

sql

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.

like image 830
sql beginner Avatar asked Jul 24 '09 18:07

sql beginner


People also ask

What is constraint in CREATE TABLE?

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.

Which key words function as constraints when creating a table?

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.

Which keyword creates user defined constraints?

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.

What are all the constraints that can be specified when the table is created?

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.


2 Answers

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
like image 63
Matthew Jones Avatar answered Sep 18 '22 12:09

Matthew Jones


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.

like image 23
Mike Dinescu Avatar answered Sep 19 '22 12:09

Mike Dinescu