Altering Table Structures with SQL Commands, Explained

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

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

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

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.

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 Altering Table Structures with SQL Commands

How do you add a column to an existing table in SQL?
Use ALTER TABLE with ADD. In MySQL, ALTER TABLE products ADD COLUMN reorder_level INT NOT NULL DEFAULT 0 works; SQL Server writes ADD without the word COLUMN. Existing rows get the default for a NOT NULL column with a DEFAULT, and NULL for a nullable column without one. SQL Server and SQLite append the new column at the end, while MySQL can place it with FIRST or AFTER.
How do you rename a column in SQL?
MySQL 8.0 or later and SQLite 3.25 or later use ALTER TABLE products RENAME COLUMN title TO name. SQL Server uses a stored procedure instead: EXEC sp_rename 'products.title', 'name', 'COLUMN'. The data stays in place, but queries, views and application code using the old name can break. SQLite updates compatible stored views and triggers during the rename, but no engine rewrites SQL kept in application code.
What is the difference between MODIFY COLUMN and ALTER COLUMN?
MySQL changes a column's type with MODIFY COLUMN, while SQL Server uses ALTER COLUMN. In MySQL, MODIFY replaces the whole column definition, so attributes you omit, such as NOT NULL or a default, can be lost. In SQL Server, a default is a separate constraint, changed by dropping the named default constraint and adding a new one. SQLite has neither form and needs a table rebuild to change a type.
Why does ALTER TABLE ADD CONSTRAINT fail on an existing table?
By default, the existing rows must already satisfy the new rule, so validation fails if any current value violates it. A CHECK fails on out-of-range values, a UNIQUE constraint on duplicate keys, and a FOREIGN KEY on orphaned references. Find violations first with a query, fix them or decide on a policy, then add the rule. MySQL enforces CHECK constraints only from version 8.0.16.

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 →