Book Contents

Book Index

Next Topic

Home

Adding Primary Key and Foreign Key Constraints

Primary Key Constraints

A primary key is a column or combination of columns that uniquely identify a row in a table. A PRIMARY KEY constraint is a rule that states that a column (or a set of columns used as a compound key) cannot be null and cannot (as a whole) contain duplicate data.

In Vertica, all dimension tables (unsegmented tables) are required to have a PRIMARY KEY column-constraint or table-constraint in order to be joined to other tables.

Primary key constraints are enforced only when loading data into a pre-join projection.

Foreign Key Constraints

A foreign key is a column that is used to join a table to other tables. A FOREIGN KEY constraint is a rule that states that a column cannot be null and contains only values from the PRIMARY KEY column of a specific dimension table.

In Vertica, fact table join columns are required to have FOREIGN KEY constraints in order to participate in pre-join projections, which provide optimal query performance.

However, fact table join columns cannot have FOREIGN KEY constraints when used in outer join queries that produce expected results. If the fact table join column has a PRIMARY KEY constraint, outer join queries produce the same result set as inner join queries. See the Using Outer Joins section of the SQL Programmer's Guide for more information.

FOREIGN KEY constraints are enforced only when loading data into a pre-join projection. Thus, if a table does not participate in a pre-join projection, it is possible to load erroneous data into that table that can cause a constrain violation error when:

Defining Constraints

There are two SQL commands that define a primary key or foreign key constraints:

Examples are shown below. See the SQL Reference Manual for detailed information about these commands.

Defining Column Constraints

To define a PRIMARY KEY constraint on a single column:

CREATE TABLE Dim1 (

C1 INTEGER CONSTRAINT Dim1pk PRIMARY KEY,

C2 INTEGER);

Because a constraint name is optional, you can write the example as:

CREATE TABLE Dim1 (

C1 INTEGER PRIMARY KEY,

C2 INTEGER);

To define a FOREIGN KEY constraint on a single column:

CREATE TABLE Fact1 (

C1 INTEGER CONSTRAINT Fact1Dim1fk FOREIGN KEY REFERENCES DIM1(C1),

C2 INTEGER);

Again, the constraint name is optional.

Defining Table (Multi-Column) Constraints

To specify multi-column (compound) keys, you must use an ALTER TABLE statement in addition to a CREATE TABLE statement. For example:

CREATE TABLE Dim1 (

C1 INTEGER,

C2 INTEGER);

 

ALTER TABLE Dim1

ADD CONSTRAINT Dim1pk PRIMARY KEY (C1, C2);

The matching FOREIGN KEY constraint would look like this:

CREATE TABLE Fact1 (

C1 INTEGER,

C2 INTEGER);

 

ALTER TABLE Fact1

ADD CONSTRAINT Fact1fk FOREIGN KEY REFERENCES Dim1(C1,C2);

Vertica recommends that you use only named table constraints.