Adding Records with the INSERT Statement, Explained

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

← 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 →

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

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.

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 Adding Records with the INSERT Statement

How do you insert multiple rows with one INSERT statement?
List several parenthesized value tuples after VALUES, separated by commas, and each tuple becomes one new row. For example, INSERT INTO customers (first_name, last_name) VALUES ('Ana', 'Ruiz'), ('Ben', 'Lee') adds two customers, and columns left out of the list receive their defaults in every row. MySQL, SQL Server, and SQLite all support this form, although SQL Server caps one VALUES list at 1,000 rows and a MySQL statement must fit the packet size.
What is the difference between leaving a column out of INSERT and inserting NULL?
Leaving a column out asks the database to use that column's default, or NULL when no default is defined, while writing NULL explicitly supplies a value, so the default is not applied. If points is NOT NULL with a default of 0, omitting it stores 0, but inserting NULL for points breaks the NOT NULL rule and the insert fails. For a nullable city column without a default, either approach stores NULL.
How do you get the ID of a newly inserted row?
Omit the generated key from the INSERT, let the database assign it, and then ask the same session for the new value. MySQL returns it with LAST_INSERT_ID() for AUTO_INCREMENT columns, SQL Server with SCOPE_IDENTITY() for IDENTITY columns, and SQLite with last_insert_rowid() for an INTEGER PRIMARY KEY. Generated keys can have gaps after failed inserts or rollbacks, so do not assume they are consecutive or compute the next one yourself.
Why does an INSERT statement fail?
An INSERT fails when a new row breaks a table rule or the statement itself is malformed. Common causes are a duplicate primary key or unique value, NULL in a NOT NULL column, a value that fails a CHECK constraint, a foreign key pointing to a missing parent row, or a column list and value list of different lengths. In InnoDB, SQL Server, and SQLite, one bad tuple normally cancels the whole multirow statement, so read the error before retrying.

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 →