ALTER TABLE
ALTER TABLE
Section titled βALTER TABLEβWhat it means
Section titled βWhat it meansβALTER TABLE modifies an existing tableβs structure β adding, changing, or dropping columns and constraints β without recreating the table or losing its existing data (for non-destructive changes).
Examples
Section titled βExamplesβALTER TABLE Employees ADD Email NVARCHAR(255);
ALTER TABLE Employees ALTER COLUMN Email NVARCHAR(320) NOT NULL;
ALTER TABLE Employees DROP COLUMN MiddleName;
ALTER TABLE Employees ADD CONSTRAINT UQ_Email UNIQUE (Email);
ALTER TABLE Orders ADD CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerId) REFERENCES Customers(Id);Common mistake
Section titled βCommon mistakeβAdding a NOT NULL column to a table that already has rows, without a DEFAULT value β SQL Server has nothing to put in that column for existing rows, and the statement fails outright.
-- Error if the table already has rows: Cannot insert the value NULL into-- column 'Email' ... does not allow nullsALTER TABLE Employees ADD Email NVARCHAR(255) NOT NULL;
-- Fix: provide a DEFAULT so existing rows get a valid valueALTER TABLE Employees ADD Email NVARCHAR(255) NOT NULL DEFAULT 'unknown@example.com';Quick practice
Section titled βQuick practiceβ-
What does
ALTER TABLE ... ADDdo?Answer
Adds a new column (or constraint) to an existing table. -
Why does adding a
NOT NULLcolumn without a default fail on a table that already has rows?Answer
SQL Server would have no value to place in that new column for the existing rows, andNOT NULLforbids leaving it empty, so the statement is rejected unless aDEFAULTis supplied. -
What clause removes a column entirely from a table?
Answer
ALTER TABLE TableName DROP COLUMN ColumnName;