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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Foreign Keys in SQL: Linking Tables Together →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is the difference between a natural key and a surrogate key?
How do you create an auto-incrementing primary key in MySQL and SQL Server?
Why are there gaps in auto-increment ID numbers?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →