UPI Study › Courses › Database Programming › Free lessons › Lesson 6.3 Free with a free account
Changing Records with the UPDATE Statement
Database Programming · Chapter 6: Data Retrieval and ModificationSection 6.3 · lesson 37 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: Removing Records with the DELETE Statement →← Data Manipulation Language (DML): Commands at a GlanceNext lesson: Removing Records with the DELETE Statement →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Changing existing rows safely with UPDATE, SET, WHERE, and constraints.
- Write UPDATE statements that change one or more columns in matching rows
- Preview an update's target rows with a SELECT that uses the same condition
- Explain why AND between assignments and a missing WHERE clause cause wrong updates
- Describe how constraints and statement atomicity reject invalid updates
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 (982 words). Read along, or search it.
Opening Question
Recording a Delivery and a Price Fix
Sofia Alvarez handles sales at Lantern Books, our fictional bookstore. She needs to record a delivery of pen sets and correct their price. One command can change both values. The difficult question is which rows it will touch, and whether every proposed value satisfies the rules. Let us make the change, inspect the evidence, and deliberately try an update that the database must reject.
Table Setup
Products With Required Fields and Checks
We start from the canonical product rows in a disposable database. Every price and quantity is an invented teaching value. Each row has an identifier, a name, a price, and stock. Required fields reject null; check constraints keep price and stock nonnegative. Run this setup. Its successful statements are quiet in this shell; we will use select to inspect the changes that follow. The declared decimal type does not enforce fixed scale in SQLite. Later queries format prices for display, without pretending formatting changes how values are stored.
Basic Syntax
UPDATE, SET, and WHERE
Read the update in three parts. Update names the target, set supplies the new value, and where chooses the matching rows. The expression multiplies each matching price by one point one. It uses that row's current price, not one shared price for every product. The condition selects two book identifiers. Run it: two rows match, and their displayed prices become twenty-seven fifty and thirty-five twenty. Products outside that condition stay unchanged. Rollback restores the baseline here; in an ordinary autocommit session, a successful standalone update is already committed.
Multiple Columns
Changing Stock and Price Together
Now Sofia records the pen delivery. Separate assignments with a comma: add ten to stock, and assign the fixed price of six fifty. The condition still selects a single identifier. All assignments apply to that matching row; columns absent from set retain their existing values. Run this file. Stock rises from twenty to thirty, and the displayed price is six fifty. One update changes both fields. Do not repeat the statement casually. An arithmetic increment is applied again on each successful run; correcting a price and adding stock are different operations.
Common Mistake
Commas, Not AND, Between Assignments
Use commas between assignments, never and. In MySQL and SQLite, and can become part of a Boolean expression, silently producing one unintended assignment. SQL Server rejects that malformed assignment pattern. A statement that runs is not necessarily a statement that performs the intended operation. Also avoid depending on a value changed earlier in set. MySQL single-table assignments generally evaluate left to right; SQL Server and SQLite use the original values.
Assignment Order
Original Values Versus Left-to-Right Updates
Here is a tiny scratch example, separate from bookstore products. Both right sides refer to the original row in SQLite. Run it: a becomes two, while b receives the original one. MySQL single-table behavior would normally give b the new two. For portable code, write independent expressions from the original inputs. When an operation genuinely needs multiple steps, make those steps explicit within a transaction.
Safe Practice
Preview the Condition With SELECT
Write the selection first, keeping the exact intended condition. These low-stock products are the candidates for a five-unit adjustment. Run the file. Four products appear in the preview, and four rows match the update. Inspect identities as well as the count. Keep the where clause when rewriting the statement as an update. Do not mechanically replace one keyword; select and update have different grammatical structures. This preview is a useful check, not a concurrency guarantee. In production, protect the actual decision with an appropriate transaction and isolation strategy.
Missing WHERE
Every Price Set to Zero
Now remove the condition in our sandbox. Every product is eligible, and zero remains a legal price under the declared check constraint. Run it: all eight rows match, and all eight prices become zero. The database cannot infer that Sofia meant only the pen set. We roll back deliberately. MySQL safe-update mode can block some broad changes, but an accepted condition can still select the wrong rows. Expect one row for a precise key change. Unexpected zero can mean a missing identifier; a large count can mean an overly broad condition.
Statement Atomicity
A Failed Check Leaves Both Rows Unchanged
Suppose one shipment adjustment subtracts six from two books. Database Basics has twelve, but Biology Guide has only five. The second result would violate the stock check. Under SQLite's default abort policy, a failed statement cannot leave only its acceptable rows updated. Run it. The diagnostic names the check, and the follow-up query still shows twelve and five. Neither row changed. That is statement atomicity: all matching changes or none. It does not mean earlier successful statements in an open transaction were automatically rolled back.
Constraint Errors
NOT NULL, Unique, and Foreign Key Rejections
Other rules also apply to updates. For this sandbox, a unique-name index and a small referencing relation add two explicit test constraints. The first attempt writes null into a required name. The second tries to reuse Notebook, which another product already owns. The third changes a referenced identifier, leaving its child without a parent. Foreign-key enforcement is enabled before the transaction starts. Run these attempts. This shell continues after each error, allowing a final query; the pen set keeps its original identifier and name. Read the named rule before adjusting the value or condition. Default abort protects each statement; other conflict policies and nontransactional engines can have different behavior.
Quick Check
A Notebook Sale With Two Assignments
A notebook sale uses a new two-field adjustment. The starting row has thirty units and a price of four fifty. What stock and displayed price will this script produce? Read both assignments and the condition. Pause and predict. Twenty-six and five fifty. The notebook satisfies the condition, so both comma-separated assignments apply to that one row. Keeping thirty ignores the stock assignment. Keeping four fifty ignores the price assignment; the comma does not make either change optional.
Key Takeaways
Target, Assignment, Evidence, and Rules
Specify the target and the assignment: update changes existing rows, and set can use fixed values or expressions. Preview the exact condition, then inspect the affected count and final values. Sofia can explain both what changed and why those rows were selected. Let constraints reject invalid values, and finish transactions deliberately. A rejected statement is a signal to investigate, not a reason to remove the rule.
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 Changing Records with the UPDATE Statement
How do you update multiple columns in SQL?
What happens if you run UPDATE without a WHERE clause?
Why should you use commas instead of AND in an UPDATE SET clause?
Does an UPDATE use original or new values when one assignment refers to another column?
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 →