UPI Study › Courses › Database Programming › Free lessons › Lesson 5.1 Free with a free account
Adding Records with the INSERT Statement
Database Programming · Chapter 5: Querying, Filtering, and Sorting DataSection 5.1 · lesson 26 of 768 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: Controlling Result Size: Limiting Query Output →← Writing Advanced SQL Queries: Techniques and PatternsNext lesson: Controlling Result Size: Limiting Query Output →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
How INSERT adds rows, applies defaults, and respects table constraints.
- Write single-row and multirow INSERT statements with an explicit column list
- Explain how omitted columns, defaults, and explicit NULL values differ
- Compare generated-key syntax in MySQL and SQL Server
- Diagnose insert failures caused by primary key, NOT NULL, CHECK, and foreign key rules
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 (920 words). Read along, or search it.
Opening Question
A Signup That Never Became a Row
Maya Rao owns Lantern Books. A customer submits a signup form, but closing the browser makes the new account disappear. The application displayed the details without storing a row. What must it send to make that registration survive? An insert adds a record to a table. We will follow the values, the defaults, and the rules that decide whether a record belongs.
Table Setup
Customers Table With Defaults and Checks
This is a disposable copy of our bookstore customers, with the same six starting records. The names and amounts are illustrative. The customer identifier is an integer primary key. First and last names are required, while city permits a missing value. Points are required too, but the default supplies zero when we leave that column out. The check prevents negative points. A default is a value the table supplies under an insertion rule. It is not permission to omit every required piece of information. Our demonstrations use SQLite. Its integer primary key can generate an unused identifier when that column is omitted. Other systems declare that behavior differently.
Basic Syntax
Inserting One Row With a Column List
Start with insert into customers, followed by an explicit column list. Values supplies one row tuple, the parenthesized group for a single new record. The first value fills the first named column. Imani fills first name, Cole fills last name, and Oslo fills city. Text uses single quotes; the point amount is numeric. The values match the listed columns by position, even when a different column order would also be legal. Run this file against a fresh database in memory. A select retrieves the stored row after the insert completes. The result contains Imani with forty points. SQLite's shell prints the select result; it does not automatically print a server-style affected-row message.
Multirow Insert
Adding Several Rows in One Statement
One insert can contain several row tuples, separated by commas. Each tuple still needs exactly the values named by the shared column list. Both new customers omit points. The schema supplies its default independently for each row; this is one statement adding two records. Batching avoids sending a separate statement for every record. It can reduce overhead, although practical batch sizes depend on the engine and application. Execute the batch and retrieve just the new identifiers. Ordering the result makes our inspection repeatable. Both records have zero points. SQL Server permits at most one thousand tuples in a direct insert values list; MySQL also has packet-size limits.
Defaults and NULL
Omitted Columns Versus Explicit NULL
Leave city and points out together. These omissions look similar in the statement, but the schema definitions give them different meanings. City has no declared default and permits null, so its stored value becomes null. Points has a declared default, so it becomes zero. Explicitly supplying null is different from leaving a column out. A null for required points would violate the rule rather than request its default. Run the query with quote around city. That SQLite display helper makes the missing marker visible rather than leaving an empty-looking terminal cell. The result separates a missing city from known zero points. Never guess whether a blank-looking result means empty text or a missing value.
Dialect Comparison
AUTO_INCREMENT, IDENTITY, and Generated Keys
These are labeled, non-run dialect fragments. MySQL declares auto increment, while SQL Server uses identity with a starting value and increment. Leave the generated column out of the insert. MySQL's last insert identifier function retrieves its generated key; SQL Server uses scope identity in its own context. SQL Server normally refuses an explicit identity value unless identity insert is enabled. MySQL permits explicit values, subject to its key rules. The identifiers need not be consecutive. Failed allocations, deletion, imports, or administrative changes can create gaps; ordinary SQLite row identifiers can also be reused. MySQL and SQL Server accept default in a values tuple. SQLite does not accept that mixed-values form, so our runnable files omit the defaulted column.
Error Handling
Reading Constraint Violations on Insert
A failed insert is a clue about the contract. A repeated primary key conflicts with uniqueness; a missing required name conflicts with not null. A negative point amount fails the check. An order referencing a nonexistent customer fails its foreign key, when that rule is enabled. A different count of columns and values fails before a valid row can be assembled. Read the message, identify the rule, then correct the statement. For ordinary transactional inserts, a bad tuple can reject the whole multirow statement. Ignore options, nontransactional tables, and conflict policies can change that behavior. Do not report a successful registration just because a button was clicked. Confirm success, then retrieve the row or generated key your application needs.
Quick Check
Predicting a Reordered Column List
A different signup changes the order of the named columns. Read the column list and the value list, then predict the new first name and points. Choose Reed with fifteen, Jules with fifteen, or Jules with zero. The select shows the stored result after this insert. Pause, and decide.
Answer
Values Follow the Listed Column Order
The answer is Jules with fifteen. The value paired with first name is Jules, even though last name was listed first. The explicit point amount replaces any need for the default. Defaults supply omitted values; they do not overwrite a valid value we provide. Reed is the surname, and zero would require leaving points out. Follow the two lists by position instead of assuming the schema's declaration order.
Key Takeaways
Confirmation Should Match a Stored Record
Back at Lantern Books, Maya's signup can now survive the browser closing. The application sends an insert, checks success, and keeps the generated identifier. Write explicit columns, align every tuple, and understand omissions. Those choices make new records intentional instead of accidental. Let constraints protect stored data, and treat rejection as information to resolve. A displayed confirmation should correspond to a stored record.
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 Adding Records with the INSERT Statement
How do you insert multiple rows with one INSERT statement?
What is the difference between leaving a column out of INSERT and inserting NULL?
How do you get the ID of a newly inserted row?
Why does an INSERT statement fail?
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 →