{
  "id": "primary-key",
  "title": "Primary Key",
  "lang": "en",
  "source_lang": "en",
  "summary": "A primary key is a designated set of columns that uniquely identifies each row in a relational database table and does not permit null values.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Primary identifier",
    "PK"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/primary-key/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/primary-key/",
      "json": "https://aiwiki.page/zh/primary-key.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A primary key is a column or combination of columns designated to uniquely identify each row in a relational database table. Its values must be unique across the table, and none of its component columns may contain a null value. A table can have several possible unique identifiers, but only one is designated as its primary key. Primary keys provide a stable way to distinguish records, connect related tables, and enforce rules about data identity."
    },
    {
      "heading": "Relational foundations",
      "text": "In the relational model, a table represents a relation, its rows represent tuples, and its columns represent attributes. A candidate key is a minimal set of attributes whose values uniquely identify every tuple in every valid state of the relation. “Minimal” means that removing any attribute would destroy this guarantee; it does not mean the key with the fewest columns among all possible keys.\n\nThe primary key is the candidate key selected as the principal identifier. Other candidate keys are commonly called alternate keys. A superkey is any set of attributes that guarantees uniqueness, whether or not it is minimal. Every candidate key is a superkey, but a superkey containing unnecessary attributes is not a candidate key.\n\nFor example, a table of employees might have both an employee number and a separately assigned, unique payroll identifier. Either could be a candidate key. Choosing the employee number as the primary key does not remove the payroll identifier’s uniqueness requirement.\n\nThese concepts are connected to functional dependencies. If \\(K\\) is a key and \\(R\\) is the complete set of attributes in a relation, then:\n\n\\[K \\rightarrow R\\]\n\nThis means that the key’s value determines every attribute value in the row. Uniqueness must be a rule of the data model, not merely a coincidence in the records currently stored."
    },
    {
      "heading": "Constraints and SQL declarations",
      "text": "In SQL, a primary key is declared using the PRIMARY KEY constraint:\n\nCREATE TABLE Customer (\n    customer_id BIGINT PRIMARY KEY,\n    email VARCHAR(254) NOT NULL UNIQUE,\n    display_name VARCHAR(100) NOT NULL\n);\n\nHere, customer_id is the primary key. The email column is an additional identifier whose uniqueness and non-nullability are independently enforced.\n\nA primary-key constraint normally has two essential effects:\n\n- Uniqueness: no two rows may have the same complete key value.\n- Non-nullability: every component of the key must have a value.\n\nA null represents missing or unknown information, rather than an ordinary value such as zero or an empty string. Prohibiting nulls ensures that each row has an available identifier.\n\nA UNIQUE constraint is not always equivalent to a primary key: nullable unique columns may be permitted, and the treatment of nulls in uniqueness checks varies across database management systems. Implementation-specific exceptions also exist to standard primary-key behavior.\n\nSQL systems generally enforce uniqueness and non-nullability but do not verify that a declared primary key is minimal in the relational-theory sense. A declaration can therefore contain redundant columns even though textbook definitions describe primary keys as selected candidate keys.\n\nA primary-key declaration does not, by itself, generate values. Automatic numbering requires a separate mechanism, such as an identity column, a sequence, or a product-specific auto-increment facility."
    },
    {
      "heading": "Single-column and composite keys",
      "text": "A primary key may contain one column or several. A multi-column primary key is called a composite primary key.\n\nCREATE TABLE Enrollment (\n    student_id BIGINT NOT NULL,\n    course_id BIGINT NOT NULL,\n    enrolled_on DATE NOT NULL,\n    PRIMARY KEY (student_id, course_id)\n);\n\nThis key permits a student to enroll in multiple courses and a course to have multiple students, while preventing duplicate rows for the same student–course pair. Neither column must be unique independently; the combination must be unique.\n\nThe key is valid only if it matches the intended rules. If a student can take the same course in different academic terms, the model must distinguish those enrollments, perhaps by adding a term identifier to the key.\n\nColumn order does not change which combinations must be unique. It can, however, affect the usefulness of the associated database index for particular queries."
    },
    {
      "heading": "Natural and surrogate keys",
      "text": "Primary keys are often classified by how their values originate.\n\nA natural key uses an identifier that already has meaning in the modeled domain, such as a product code or an officially assigned registration number. Natural keys can make relationships understandable without an additional lookup. Their suitability depends on whether the identifier is genuinely unique, always available, and sufficiently stable.\n\nA surrogate key is introduced specifically to identify a database record, rather than to express a business property. Common examples include generated integers and universally unique identifiers (UUIDs).\n\nSurrogate keys separate internal row identity from changing business information. They do not eliminate the need to enforce business uniqueness. For example, assigning different generated identifiers to two records does not establish that those records represent different customers.\n\nNeither approach is universally preferable. The choice depends on key width, stability, interoperability, generation requirements, and the rules governing the entities being represented. A primary key is not inherently immutable, but changing widely referenced key values can require substantial coordination."
    },
    {
      "heading": "Relationships and referential integrity",
      "text": "A foreign key is a column or group of columns whose values reference a permitted identifier in another table, or in the same table. Foreign keys commonly reference primary keys, although supported unique keys may also serve as targets.\n\nFor example, an order table can contain a customer_id foreign key referencing the customer table’s primary key. This allows many orders to refer to one customer without repeating the customer’s details.\n\nSuch constraints enforce referential integrity: a non-null reference must match an eligible referenced row. Database systems can reject changes that would leave invalid references or apply declared actions, such as cascading updates or deletions. These actions belong to the foreign-key definition; they are not automatic consequences of declaring a primary key.\n\nIn entity–relationship modeling, identifiers and relationships help translate conceptual entities into relational tables. Tables representing many-to-many relationships often use the two participating identifiers as a composite primary key."
    },
    {
      "heading": "Indexing and physical storage",
      "text": "Most relational database systems enforce primary-key uniqueness through a unique index or an equivalent indexing mechanism. This can support efficient row lookup and joins, but a primary key is fundamentally a logical constraint, not a particular storage layout.\n\nA primary key does not universally imply that:\n\n- rows are physically stored in key order;\n- the primary-key index is clustered;\n- query results are returned in key order;\n- the identifier is numeric or sequential.\n\nThese properties depend on the database engine and table configuration. Query results require an explicit ORDER BY when a particular order is needed.\n\nKey design can affect storage and performance. Wide keys consume more index space and may be repeated in referencing tables. Some storage engines also include the primary key in secondary index entries, increasing the cost of a wide identifier.\n\nSequential identifiers can favor localized insertion but may concentrate concurrent writes on a small part of an index. Randomly distributed identifiers can spread insertion activity while increasing page changes or fragmentation in some storage structures. The trade-off depends on the implementation and workload."
    },
    {
      "heading": "Scope and limitations",
      "text": "Primary-key uniqueness is normally scoped to one table. The same numeric value can identify unrelated rows in different tables or independently operated databases.\n\nIn distributed systems, independently generated keys may collide when records are merged unless generation is coordinated or uses a sufficiently large identifier space. UUIDs reduce dependence on a central allocator, but their collision properties depend on the version and generation procedure. A uniqueness constraint remains a separate safeguard.\n\nA primary key also does not establish that a record is accurate, current, or semantically distinct from every other record. Detecting duplicate real-world entities requires additional rules and data-quality processes.\n\nFinally, an identifier is not an authorization mechanism. Knowing or guessing a row’s key must not, by itself, grant access to that row. Random-looking identifiers can make enumeration harder, but access control must be enforced independently."
    }
  ],
  "links": [
    "relational-database",
    "sql",
    "database-management-system",
    "database-index",
    "foreign-key",
    "distributed-computing",
    "data-quality"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}