Primary Keys in SQL: What They Are and How to Use Them

UPI Study › Courses › Database Programming › Free lessons › Lesson 2.5 Free with a free account

Primary Keys in SQL: What They Are and How to Use Them

Database Programming · Chapter 2: Normalization and Data IntegritySection 2.5 · lesson 12 of 7610 min · free with a free account

← Achieving Third Normal Form (3NF): Walkthrough and ExamplesNext lesson: Foreign Keys in SQL: Linking Tables Together →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Choose, declare, and generate primary keys that identify each row.

  • Explain how a primary key enforces unique, required row identity
  • Distinguish candidate, alternate, natural, surrogate, and composite keys
  • Compare generated keys in SQLite, MySQL AUTO_INCREMENT, and SQL Server IDENTITY
  • Choose a stable key with enough range and expect gaps in generated values

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,181 words). Read along, or search it.

Opening Question

Pointing to Exactly One Customer

Two customers can share a name or city. What should an order store so it still points to exactly the intended person? Our fictional Lantern Books subset uses customer identifier as the primary key. Asha, Ben, and Chen each have a different identifier. The key supplies identity. SQLite does not enforce the declared text lengths here; type details come later.

Key Rules

Unique and Required Identity

Primary key enforces uniqueness and required identity. This explicit integer declaration also writes not null, making the requirement visible and portable. Attempting customer three again conflicts with Chen's existing identifier. Attempting a null identifier breaks the required-value rule. A table has one primary key, although that key can contain several columns. These are two rejected inserts, not two primary keys. Run the attempts, then inspect the surviving customers. SQLite reports its own diagnostic wording; MySQL and SQL Server use different messages. Both failures are reported, and the original three customers remain. With this declaration, missing identity is rejected instead of generated.

Stability

Identity That Survives Changes

Stable means continuing to identify the same row. Uniqueness enforcement cannot decide whether an identifier retains its intended meaning. Keep identity when a customer moves or changes a name. Referencing orders depend on it. Supporting indexes speed lookup and enforce uniqueness. SQLite's integer row identifier is a special implementation case. A key remains a label. It is not a row position, a business ranking, or a promise of continuous numbers.

Candidate Keys

Alternate Keys with NOT NULL UNIQUE

A candidate key is a minimal column set that identifies rows under the business rules. Choosing one makes it the primary key. Other candidate keys become alternate keys. In this separate account extension, email is required and unique because the application explicitly requires distinct addresses. Not null unique expresses that alternate-key rule. A second primary key would be invalid, and a mere unique-today observation would not establish the requirement. Run the duplicate-email attempt, then inspect the stored account. The identifier differs, but the alternate-key rule still applies. The duplicate email is rejected, and Asha's account remains. Several unique constraints can coexist with the table's single primary key.

Unique and Null

How Engines Treat Nulls in Unique Columns

In SQLite and MySQL, an ordinary nullable unique column can contain several null values. Uniqueness still rejects repeated non-null values. SQL Server's ordinary single-column unique constraint permits one null. Adding not null makes an alternate key required in all three engines. An empty string is a stored text value, not a null marker. Decide whether missing values are permitted before choosing the constraint.

Key Kinds

Natural, Surrogate, and Composite Keys

A natural key comes from the domain, such as a currency code. Verify its uniqueness and availability for the entity. A surrogate is an artificial identifier. It supplies identity, but does not validate the other facts. A composite uses several columns together. Natural or surrogate describes origin; composite describes structure, so categories can overlap.

Composite Keys

The Order and Product Pair

An order can contain several products, and a product can appear on several orders. Neither identifier alone identifies an item row. The order-product pair is the composite primary key. Our shop permits one line per product per order, with quantity carrying repetition. Every component is required. A related table referring to this composite identity would need the complete pair, rather than one arbitrarily chosen column. Run the attempt to add the same pair again. The new quantity does not create a new identity under our stated rule. The duplicate pair is rejected, leaving the original quantities. A design allowing separate lines for one product would need another line identifier.

Generated Values

SQLite INTEGER PRIMARY KEY Behavior

Generating a value and enforcing identity are different jobs. In SQLite, the exact declaration integer primary key aliases its internal row identifier. Omitting this column generates an unused identifier. Explicit null also requests generation here, unlike the earlier I N T declaration with not null. Do not transfer that behavior to every database. Ordinary SQLite primary keys of other types can even allow null, unless not null is explicit. Run this fresh membership example, where both rows request generated identity. Neither request supplies an actual missing stored key. The resulting identifiers are one and two. This engine-specific behavior is why exact data-type spelling matters when teaching keys.

Dialect Syntax

AUTO_INCREMENT Versus IDENTITY

These are non-run alternatives. MySQL uses auto increment; SQL Server uses identity with a seed and increment, shown here as one and one. Omit the identifier from the insert column list to request generation. Keep primary key, because a generator is not a replacement for identity enforcement. MySQL retrieves the generated value with last insert I D. SQL Server's scope identity returns the last identity generated in the current scope. Explicit identifiers are allowed by MySQL under its counter rules. SQL Server normally needs identity insert enabled; neither declaration is SQLite syntax.

Gaps and Reuse

Do Not Renumber Generated Identifiers

Generated identifiers can have gaps after deletions or failed attempts. Never renumber rows to make the labels look consecutive. SQLite without auto increment can reuse a deleted maximum. Its auto increment keyword prevents reuse of previously committed row identifiers, with additional overhead. MySQL and SQL Server normally advance their generators, but manual values and reseeding complicate any absolute never-reuse promise. Gaps do not indicate missing current rows. Run both SQLite declarations after deleting identifier three. Each receives another automatic insert in its own separate table. Ordinary generation returns three, while auto increment returns four. The primary-key rule is satisfied in both tables; allocation history differs.

Quick Check

Counting Rows Versus Reading IDs

A new membership table contains identifiers four and nine. The displayed statement asks for count star,. What does that query report: four records, nine records, or two records? Pause, and predict the result. Two records is the answer. There are two stored rows, regardless of the identifier values or the gaps between them. Run the counting query on this fresh membership sandbox. Count star counts rows, while the key column supplies their identities. The result is two. Four and nine are labels from individual rows, so neither one can serve as the row count.

Choosing a Key

Uniqueness, Stability, Availability, and Length

Test uniqueness, stability, availability, and length. Names, emails, and phone numbers may repeat, change, or be missing. A short surrogate often suits people or products. A composite may suit links; a stable official code may suit a natural key. Choose range for expected allocations. Signed thirty-two-bit integers end just above two billion; signedness choices and engines differ. Avoid sensitive or changeable identifiers. Changing a key affects every referencing relation.

Quick Check

A Repeated Currency and Date Pair

A separate rate sandbox uses currency and effective date together as its primary key. Two inserts repeat that pair, with different rate values. Does one quote survive, do both survive, or does the error remove both? Pause, and decide. One quote survives. The second insert repeats the full key, and changing a non-key rate does not give the row a new identity. Run the statements, then inspect the remaining quote. The successful earlier insert is independent of the rejected later statement. The original rate remains. Both rows cannot share the key, and the failed ordinary insert does not erase the previously stored row.

Key Takeaways

One Primary Key, Stable Identity

Choose one primary key for unique row identity. Explicit required components improve portability. Candidates offer possible identities; alternate keys preserve unchosen candidates. Composite keys need their identifying components together. Generators assign labels; constraints enforce rules. Keep identity stable, expect gaps, and count rows with a counting query.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Primary Keys in SQL: What They Are and How to Use Them

What is a primary key in SQL?
A primary key is the column, or set of columns, that uniquely identifies each row in a table. It rejects duplicate values and is meant to be required, and a table has one primary key even when that key has several columns. Write NOT NULL explicitly in portable designs, because SQLite allows nulls in some primary key columns that are not declared as INTEGER PRIMARY KEY.
What is the difference between a natural key and a surrogate key?
A natural key comes from the business domain, such as a currency code, while a surrogate key is an artificial identifier, such as a generated customer number. Before using a natural key, check that every instance has one and that it stays unique and stable; names, emails, and phone numbers often fail that test. A surrogate supplies identity but does not validate other facts, so real-world values may still need UNIQUE constraints.
How do you create an auto-incrementing primary key in MySQL and SQL Server?
In MySQL, add AUTO_INCREMENT, as in id INT AUTO_INCREMENT PRIMARY KEY; in SQL Server, use IDENTITY with a seed and increment, as in id INT IDENTITY(1,1) PRIMARY KEY. Leave the column out of the INSERT column list to have a value generated. Keep the PRIMARY KEY declaration, because a generator does not replace identity enforcement. Read the new value with LAST_INSERT_ID() in MySQL or SCOPE_IDENTITY() in SQL Server.
Why are there gaps in auto-increment ID numbers?
Gaps are normal, because generated identifiers can be used up by deleted rows and failed or rolled-back inserts without being handed out again. MySQL and SQL Server generators normally keep advancing. SQLite's INTEGER PRIMARY KEY can reuse a deleted maximum value, while its AUTOINCREMENT keyword prevents reuse of earlier values. Do not renumber rows to close gaps; other tables reference those keys, and a key is a label rather than a row count.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →