Changing Records with the UPDATE Statement, Explained

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

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

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

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.

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 Changing Records with the UPDATE Statement

How do you update multiple columns in SQL?
List each assignment in the SET clause separated by commas, as in UPDATE products SET stock = stock + 10, price = 6.50 WHERE product_id = 17. Both columns change together in each matching row, while columns that are not named keep their current values. Because stock = stock + 10 builds on the current value, running the same statement twice adds 20, so record whether a change has already been applied.
What happens if you run UPDATE without a WHERE clause?
Without a WHERE clause, an UPDATE changes every row in the table, as long as constraints allow it and no safety setting such as MySQL's safe-update mode blocks the statement. UPDATE products SET price = 0 would set every price to zero. Before running a broad update, preview the target rows with a SELECT using the same condition, check the count, and run the change inside a transaction.
Why should you use commas instead of AND in an UPDATE SET clause?
Commas separate assignments, while AND inside a SET expression becomes part of a single value. In MySQL and SQLite, SET stock = stock + 10 AND price = 6.50 assigns the result of a logical test, typically 1 or 0, to stock and leaves price unchanged. SQL Server rejects the statement with a syntax error. Write SET stock = stock + 10, price = 6.50 so each column gets its own assignment.
Does an UPDATE use original or new values when one assignment refers to another column?
It depends on the system. SQL Server and SQLite evaluate every assignment using the row's original values, so SET a = a + 1, b = a gives b the old value of a. MySQL single-table updates apply assignments from left to right, so b receives the new value. For portable code, write each assignment from the original values or split dependent changes into separate statements inside one transaction.

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 →