UPI Study › Courses › Database Programming › Free lessons › Lesson 9.11 Free with a free account
Altering Table Structures with SQL Commands
Database Programming · Chapter 9: Subqueries, Views, and IndexesSection 9.11 · lesson 59 of 769 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: Dropping Columns and Rows from Tables →← Building and Using Temporary Tables in SQLNext lesson: Dropping Columns and Rows from Tables →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Add, rename and change columns and constraints without losing data.
- Add columns with defaults or NULLs and predict the values existing rows receive
- Rename and modify columns using MySQL, SQL Server and SQLite syntax
- Add constraints only after checking that existing data satisfies them
- Plan schema changes around locks, dependencies and recovery
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,079 words). Read along, or search it.
Opening Problem
Changing the Catalog Without Losing Rows
Maya Rao, Lantern Books' owner, wants a reorder field and clearer product labels. Leo Park, the developer, must change the schema without losing existing catalog rows. What values should old rows receive, which callers need updating, and how could a short change block a busy application? Alter table is a migration tool. Its syntax is only the beginning of the decision.
Sample Database
Starting Shop Data for Migrations
Our examples use Lantern Books, a fictional campus bookstore. This disposable database starts with the shared course data. Customers and products hold people and inventory. Prices and quantities are illustrative, and each lesson resets its own copy. Orders link to customers, while order items link orders to products. Foreign key checks are enabled for this connection. Save the setup file, then run it against a fresh shop database. Successful creation prints no rows here. Later commands reopen that database file. These examples use the real SQLite shell, and server dialect differences will be labeled.
Rehearsal Copy
A Disposable Product Table and View
We start with an explicitly disposable product copy. It contains the four books, with chosen column definitions and a small dependent view. The original products table stays intact. A migration rehearsal should make its target and recovery boundary unambiguous. Alter table changes an existing table's structure. Some actions edit metadata, while others validate or rewrite stored data. Run the rehearsal setup. The count establishes how many rows we expect to retain through the following changes. Four rows were copied. The view also gives us a stored dependency to inspect when a column name changes.
Adding Columns
Defaults and Nulls for Existing Rows
Add column introduces a new attribute. Our required reorder level has a zero default, while the optional stock code permits null. Existing rows receive the added column's logical default or null. For a populated required column, supply a suitable default or plan a backfill. MySQL accepts add column, while SQL Server writes add without column. SQLite supports this demonstrated add form, with additional restrictions. Run the additions. We explicitly name the displayed columns, avoiding assumptions about where a new column appears. Every book has reorder level zero and a missing stock code. Adding a required field did not remove its product row.
Renaming Columns
RENAME COLUMN and Stored Views
Rename column changes the name while retaining its data. This statement uses syntax supported by our SQLite version and modern MySQL. SQL Server instead uses the rename procedure with the old table-and-column name. Search callers before relying on a renamed interface. SQLite updates compatible stored views during a rename. It cannot rewrite external application sequel, and ambiguous stored references can make the rename fail. Run the rename and both reads. The first uses the new column name; the second exercises the stored view created earlier. The four titles remain, and the view still reads four rows. Dependency behavior is engine-specific, so this result is not a universal promise.
Changing Types
MODIFY COLUMN Versus ALTER COLUMN
Changing a type uses modify column in MySQL and alter column in SQL Server. Restate the intended properties deliberately. MySQL modify can discard omitted attributes. SQL Server defaults are separate constraints; replace the named old default before adding its replacement. A changed default applies to later inserts that omit the column. It does not rewrite existing values or replace an explicitly supplied null. These are non-run server alternatives. MySQL can place a new column first or after another; SQL Server and SQLite append new columns. The stock-code addition here replaces the earlier addition, rather than adding it twice. SQLite three point forty-three needs a rebuild for type or default alterations.
Adding Constraints
Existing Data Must Pass New Rules
An existing table can receive new constraints, but its existing data must satisfy the enforced rule. Validation can fail before the change completes. Check rejects values outside a condition; unique prevents duplicate keys; foreign keys require valid references. A missing primary key can also be added when its requirements hold. Our optional stock codes are all null. MySQL permits multiple nulls under a unique rule; ordinary single-column SQL Server uniqueness would reject that set. These are non-run server examples. MySQL enforces check constraints from eight point zero point sixteen; earlier versions should not be trusted to enforce the written check. Create index works on both servers, while MySQL also offers add index inside alter table. Do not execute both alternative index definitions.
Preflight Check
Measuring Values Before Narrowing a Column
Before narrowing a column, inspect the values already stored. This preflight measures name length and checks missing stock codes. MySQL uses character length, while SQL Server commonly uses len; trailing-space rules and storage types require attention there. Numeric conversions can fail, lose information, or round. MySQL strict settings matter, and SQLite's flexible type declarations do not enforce varchar length or decimal scale. Run the preflight before proposing a ten-character field. The report identifies names that would not fit the intended new limit. The longest name has nineteen characters, and all four codes are missing. The flagged titles need a deliberate policy before a restrictive migration.
Locks and Recovery
Schema Locks and Rollback Differences
An alteration needs schema coordination. A long-running query or open transaction can delay the required lock, and later work can queue behind it. Some operations are quick metadata edits; others scan or rewrite many rows. Online support and blocking behavior depend on the operation, engine, and version. Test on a copy, back up, change in a quiet period, and monitor active transactions. One small tested change is easier to diagnose than an opaque bundle. MySQL algorithm equals instant can refuse an unsupported instant operation, instead of silently accepting a table rebuild. It does not eliminate every locking concern. SQL Server supports transactional alter operations. MySQL alter table generally commits implicitly, so a reverse migration and backup matter; rollback is not interchangeable across engines.
Quick Check
Default, Update and New Insert Total
A fresh table already contains one row. The script adds a required priority with a default, changes the old row, and inserts another row without specifying priority. What total is printed: four, seven, or eleven? Pause, and predict. Eleven is printed. The old row receives the added default, then its explicit update changes that priority to seven. Run the script. The later insert omits priority, so it receives four; seven plus four is eleven. Seven ignores the newly inserted row. Four ignores the explicit update and treats the default as though it overwrote every value continuously.
Key Takeaways
Rehearse Data, Callers and Recovery
Maya and Leo can keep the catalog rows while changing their structure. Give existing rows a valid path into every new definition. Use the engine's syntax, distinguish added defaults from later default changes, and name columns explicitly in queries and inserts. Check conversions, dependencies, and locks before changing a live table. A successful rehearsal includes the data, the callers, and a workable recovery plan.
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 Altering Table Structures with SQL Commands
How do you add a column to an existing table in SQL?
How do you rename a column in SQL?
What is the difference between MODIFY COLUMN and ALTER COLUMN?
Why does ALTER TABLE ADD CONSTRAINT fail on an existing table?
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 →