Primary keys

Each table in a relational database should have a primary key. The primary key is a column, or set of columns, that uniquely identifies each row. No two rows in a table can have the same primary key value.

Examples

In the SQL Anywhere sample database (samples-dir\demo.db), the Employees table stores personal information about employees. It has a primary key column named EmployeeID, which holds a unique ID number assigned to each employee. A single column holding an ID number is a common way to assign primary keys, and has advantages over names and other identifiers that may not always be unique.

A more complex primary key can be seen in the SalesOrderItems table of the SQL Anywhere sample database. The table holds information about individual items on orders from the company, and has the following columns:

  • ID   An order number, identifying the order the item is part of.

  • LineID   A line number, identifying each item on any order.

  • ProductID   A product ID, identifying the product being ordered.

  • Quantity   A quantity, displaying how many items were ordered.

  • ShipDate   A ship date, displaying when the order was shipped.

A particular sales order item is identified by the order it is part of and by a line number on the order. These two numbers are stored in the ID and LineID columns. Items can share a single ID value (corresponding to an order for more than one item) or they can share a LineID number (all first items on different orders have a LineID of 1). No two items share both values, and so the primary key is made up of these two columns.