…
…
SQL and Database Fundamentals · Lesson 33 / 41 · Data modeling
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The student records database has been in use for a year, and new needs have come up: store each student's phone number, add a rule to the term dates, rename a column, and remove an unused backup table. The tables hold 120 students and hundreds of enrollments, so you need to change them without dropping and rebuilding them.
In this unit you built tables from scratch. In lesson 28 you wrote columns and types with CREATE TABLE, in lessons 29 and 30 you added constraints and foreign keys, and in lessons 31 and 32 you modeled a club system and normalized tables. In all of them the tables were empty, so no row could break when you wrote a rule. In real life, a design is never finished once and for all. As the system is used, new requests arrive: "Let's store the student's phone too," "People misread this column name," "This rule should have been there from the start." At that point the tables hold data, and that data must not be lost.
In this lesson you will:
DROP TABLE) and emptying it (TRUNCATE).The crude way to change a table is to drop it and build it again. With data inside, that is not acceptable: the information of 120 students, 781 enrollments, and all the foreign keys that point to them would be gone. ALTER TABLE changes the structure of an existing table while its rows stay in place. The command always starts with ALTER TABLE table_name, followed by what will change: ADD COLUMN, DROP COLUMN, RENAME COLUMN, ALTER COLUMN, ADD CONSTRAINT.
The main idea of this lesson is hidden in that comparison. In an empty table, every change is accepted. In a table with data, every change is applied to all the existing rows: when a new column is added, every row must get a value for it; when a new constraint is added, every row must satisfy that rule; when a column type changes, every value must be convertible to the new type. If a single row does not fit, PostgreSQL rejects the whole change and the table stays as it was.
The first request is the phone number. ADD COLUMN adds a new column to the table; the column definition is written as in CREATE TABLE: name, type, and optionally constraints.
Example 1 (case): The phone column
ALTER TABLE student ADD COLUMN phone VARCHAR(15); SELECT student_no, first_name, phone FROM student ORDER BY student_no LIMIT 3;
| student_no | first_name | phone |
|---|---|---|
| 202302001 | Camila | NULL |
| 202302002 | Rosa | NULL |
| 202302003 | Pablo | NULL |
The column was added, and its value is NULL for all 120 existing students. This makes sense: PostgreSQL does not know anyone's phone number, and for an unknown value it writes the NULL you met in lesson 7. The new column stays empty until you give it values.
Dropping is just as easy: after ALTER TABLE department DROP COLUMN founded_year;, SELECT * FROM department shows only the id, name, and faculty columns. That ease is a trap: DROP COLUMN deletes the column together with every value in it, and once the change is permanent, those values come back only from a backup.
A new column does not have to start empty. If you give a DEFAULT, the existing rows get that value. The cell below adds a required boolean column called active to students; every existing student counts as active. Run it, then try two tasks:
1. Delete the DEFAULT TRUE part and run it again. What does the error message say?
2. Write DEFAULT FALSE and run it. Which value did the existing students get?
Try it now· not graded; doesn't affect progress
In the first task you saw an error. First predict the cause:
Why can't ADD COLUMN active BOOLEAN NOT NULL (with no default) be added to a table that has rows?
The exact error message is:
OutputALTER TABLE student ADD COLUMN active BOOLEAN NOT NULL;
ERROR: column "active" of relation "student" contains null valuesPostgreSQL says "the active column contains NULL values", yet you just added the column. What it means is that at the moment you try to add it, the 120 rows would receive NULL for this column. There are two ways out. The first is to give a default in one step: ADD COLUMN active BOOLEAN NOT NULL DEFAULT TRUE. If there is a meaningful starting value for all students, this way is clean. The second is to add the column first while allowing NULL, fill in the values, and then set the rule: ALTER TABLE student ALTER COLUMN active SET NOT NULL. If the values differ from person to person, as with phone numbers, the second way is the only honest one. You will learn to fill in values (UPDATE) in lesson 35.
The ects column in the course catalog is jargon for international students; a clearer name is ects_credits. RENAME COLUMN old TO new changes the name of a column, and RENAME TO new_name changes the name of a table.
Example 2 (case): The new name of the ects column
ALTER TABLE course RENAME COLUMN ects TO ects_credits; SELECT code, ects_credits FROM course WHERE code IN ('CPR101', 'CPR102') ORDER BY code;
| code | ects_credits |
|---|---|
| CPR101 | 6 |
| CPR102 | 6 |
The values stayed the same; only the label changed. But what happens to a report query written yesterday that still uses the old name?
After the ects column is renamed to ects_credits, this query is run. What happens?
SELECT code, ects FROM course;
Renaming is one line as a command, but its effects are wide. All queries that use that column, saved reports, the views you will see in lesson 38, and the application code that connects to the database break at the same time. This is why a rename is not done on its own: first you find every place that uses the name, then you rename, then you update them all together. This is where the importance of choosing good names from the start comes from; it is why we spent so much time on naming rules in lesson 28.
ALTER COLUMN column TYPE new_type changes the type of a column. While doing this, PostgreSQL tries to convert every value to the new type one by one. If the conversion succeeds for every value, the change is accepted. A course offering has at most 60 seats, and for numbers this small SMALLINT is enough:
OutputALTER TABLE course_offering ALTER COLUMN capacity TYPE SMALLINT;
-- accepted; information_schema.columns now shows data_type = smallintA type change is not always this smooth. Two examples:
OutputALTER TABLE student ALTER COLUMN city TYPE INTEGER;
ERROR: column "city" cannot be cast automatically to type integer
ALTER TABLE student ALTER COLUMN first_name TYPE VARCHAR(4);
ERROR: value too long for type character varying(4)In the first, PostgreSQL refuses to move from text to a number on its own; anyway, "Port Alder" cannot be converted to a number. The second is familiar from lesson 25: a name longer than four characters (Anika, Felix) does not fit the new limit, and one long name stops the whole change. A type change does not always work; it works as long as the data fits the new type.
If you want to say how the conversion should be done yourself, you add USING: ALTER TABLE student ALTER COLUMN student_no TYPE BIGINT USING student_no::bigint; works, because every student number in the case consists of digits. But working does not mean it is right. Remember lesson 25: a student number is an identifier, you do not add it up, and it can start with zero. Converting an identifier to a number will swallow the zero when a number like 0123 arrives later. USING is an escape hatch, not a replacement for a decision.
The same ALTER COLUMN pattern changes other properties of a column too: SET DEFAULT and DROP DEFAULT change the default, and SET NOT NULL and DROP NOT NULL change the emptiness rule. For example, the default of has_scholarship is false; after ALTER COLUMN has_scholarship DROP DEFAULT, column_default shows NULL in information_schema.columns, and from then on a row inserted without scholarship information gets an error. What about the emptiness rule?
Remember lesson 26: in the case, 9 students have no email address. What happens when this command is run?
ALTER TABLE student ALTER COLUMN email SET NOT NULL;
SET NOT NULL needs the column to have no NULL at all. Before you add it, you can check with the pattern from lesson 11: SELECT COUNT(*) - COUNT(email) FROM student; returns 9. The same query returns 0 for city, so ALTER COLUMN city SET NOT NULL is accepted. Adding NOT NULL is not always rejected; it is rejected only if the column has empty values.
Constraints can be added later too. The named-constraint syntax you learned in lesson 29 is used here with ADD CONSTRAINT. A rule for the term table, "the end date must come after the start date":
Example 3 (case): A rule for the term dates
ALTER TABLE term ADD CONSTRAINT term_dates CHECK (end_date > start_date); SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid = 'term'::regclass AND contype = 'c';
| conname | definition |
|---|---|
| term_dates | CHECK ((end_date > start_date)) |
The constraint was added, because in all three terms the end date comes after the start date. Since the constraint has a name, it can be removed when needed with ALTER TABLE term DROP CONSTRAINT term_dates;. Unnamed constraints can be removed too, but first you have to find the name PostgreSQL gave in pg_constraint; this is why we asked you to name your constraints in lesson 29.
Now a rejected constraint. The scholarship committee wants to put the rule "GPA cannot go below 1" in the database:
OutputALTER TABLE student ADD CONSTRAINT gpa_min CHECK (gpa >= 1);
ERROR: check constraint "gpa_min" of relation "student" is violated by some row"A constraint applies only to rows added from now on" is a common misunderstanding. Before PostgreSQL accepts a new constraint, it checks all the existing rows; if even one row does not follow the rule, the constraint is not added. The error message says "some rows break the rule" but not which ones. Finding them is your job, and you do not need to learn anything new for it: query the opposite of the rule with WHERE.
OutputSELECT COUNT(*) FROM student WHERE gpa < 1;
-- 6There are 6 students with a GPA below 1; the lowest is 0.14. There are two options: if the data really contains errors, fix the data first and then add the rule; if the data is correct, the rule is wrong and you pick a threshold that fits the data. Here the grades are real, so the rule is the wrong part. This behavior is a good thing: the database tells you "this rule does not match today's reality." The pattern is always the same: query the data first, then add the rule.
In the cell below, the rejected command is ready. Run it and see the error. Then:
1. Delete the command and write a diagnostic query that lists the students who break the rule: first name, last name, and GPA, from smallest to largest. You should see 0.14 in the first row.
2. Add the rule again with a threshold that fits the data: CHECK (gpa >= 0). This time no error should come.
Try it now· not graded; doesn't affect progress
A few more examples of accepted constraints: ALTER TABLE course ADD CONSTRAINT course_dept_name UNIQUE (department_id, name); is added, because no department has two courses with the same name. ALTER TABLE student ADD CONSTRAINT enrollment_birth CHECK (enrollment_date > birth_date); is added too; every student enrolled after being born. Even ALTER TABLE student ADD CONSTRAINT email_unique UNIQUE (email); is added without an error. But remember what you learned in lesson 29: UNIQUE counts a difference in letter case and a leading space as different values. Adding the constraint means "right now there are no two addresses written the same"; it does not say the addresses are clean. In the case, 17 addresses written in capital letters or with spaces are still there.
Now use everything you have learned together. Match each of the six commands with what PostgreSQL will say. When you decide, ask two questions: "What does this change ask from the existing rows?" and "Is another table connected to this table?"
Match each command with its result in the case database.
For each row, pick its match from the list, then check.
ALTER TABLE student ADD COLUMN notes TEXT;ALTER TABLE student ADD COLUMN active BOOLEAN NOT NULL;ALTER TABLE course_offering ALTER COLUMN capacity TYPE SMALLINT;ALTER TABLE student ADD CONSTRAINT gpa_min CHECK (gpa >= 1);DROP TABLE department;TRUNCATE enrollment;The last request is to remove an unused backup table. There are two commands here, and they are often confused. DROP TABLE destroys the table with its structure, meaning its columns, constraints, and all the rows inside. TRUNCATE deletes all the rows at once but leaves the table, its columns, and its constraints in place.
Foreign keys come into play here too. Dropping or emptying a table that other tables reference would leave the rows in those tables without an owner. PostgreSQL allows neither:
OutputDROP TABLE department;
ERROR: cannot drop table department because other objects depend on it
TRUNCATE department;
ERROR: cannot truncate a table referenced in a foreign key constraintThe enrollment table is at the very end of the chain: it references other tables, but nothing references it. So TRUNCATE enrollment; is accepted, and the table goes from 781 rows to 0. If you try to drop a table that does not exist, DROP TABLE backup; gives the error table "backup" does not exist, while DROP TABLE IF EXISTS backup; passes silently if the table does not exist. This form is common in setup scripts.
Example 4 (case): Emptying a backup table
Let's take a backup of the students with a scholarship using CREATE TABLE ... AS from lesson 32, then empty it:
CREATE TABLE scholarship_backup AS SELECT student_no, first_name FROM student WHERE has_scholarship; TRUNCATE scholarship_backup; SELECT (SELECT COUNT(*) FROM scholarship_backup) AS row_count, COUNT(*) AS column_count FROM information_schema.columns WHERE table_name = 'scholarship_backup';
| row_count | column_count |
|---|---|
| 0 | 2 |
The backup table was built with 28 rows; after TRUNCATE the row count is 0, but the two columns are still there. The table is ready to be filled again. If you had written DROP TABLE scholarship_backup; in the same place, the last query would return 0 for column_count too, because the table itself would be gone. TRUNCATE is the right choice for report tables that are emptied and refilled every night, and DROP TABLE is the right choice for a table that is no longer needed at all. Deleting rows one by one or by a condition is the job of another command: you will see DELETE in lesson 36; TRUNCATE takes no condition and deletes everything.
Which command for each job?
For each row, pick its match from the list, then check.
ects column to ects_creditsDROP, TRUNCATE, and DROP COLUMN are the most dangerous commands, because they destroy data. In a real system, a backup is taken before you run them, and the command is tried first on a test database. A change on a live system is made at an hour when users are least affected. In lesson 37 you will see how to undo a change before it becomes permanent, using transactions.
Tracking changes is part of the job too. Teams write every change to the table structure into numbered SQL files called migrations: 001_student_table.sql, 002_phone_column.sql. This way it is known which change was made when and why, and the same changes can be applied in the same order first on a test environment and then on the live system. Nobody types ALTER TABLE by hand on a live database.
The hardest decisions come when the requested rule conflicts with today's data:
On the live system, you are asked to add a required phone column to the student table. None of the 120 students has a phone number in the system yet. What do you do?
Pick an option and see what happens. There are no points; you can try the other options too.
The same rules apply in every database. The product team of the Earbud music app asks for two changes: the listening time in plays must be greater than zero, and listeners should get an optional birth year column.
Example 5 (outside the case): A rule and a column in the Earbud database
ALTER TABLE play ADD CONSTRAINT seconds_positive CHECK (seconds_played > 0); SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid = 'play'::regclass AND contype = 'c' ORDER BY conname;
| conname | definition |
|---|---|
| play_seconds_played_check | CHECK ((seconds_played > 0)) |
| seconds_positive | CHECK ((seconds_played > 0)) |
The constraint was added, but the result shows a surprise: the same rule already existed in the table. It was written without a name next to the column when the table was created, and PostgreSQL gave it the name play_seconds_played_check. Two identical rules do not cause an error, but they are unnecessary; so the new one is removed with ALTER TABLE play DROP CONSTRAINT seconds_positive;. The lesson: looking at pg_constraint before adding a rule is as good a habit as looking at the data before adding it.
The birth year column is easy: after ALTER TABLE listener ADD COLUMN birth_year INTEGER;, the information_schema.columns table shows 7 columns for listener, the last one birth_year | integer. Because the column allows NULL, existing listeners start empty and nothing is rejected. The team is now thinking about one more rule:
The team wants to add CHECK (seconds_played <= 600) (a play lasts at most 10 minutes) to the play table. Is it accepted?
ALTER TABLE play ADD CONSTRAINT seconds_max CHECK (seconds_played <= 600);
After gpa_min is rejected, first the rows that break the rule are listed, then the rule is added with a threshold that fits the data.
SELECT first_name, last_name, gpa FROM student WHERE gpa < 1 ORDER BY gpa;
| first_name | last_name | gpa |
|---|---|---|
| Adaeze | Álvarez | 0.14 |
| André | Silva | 0.50 |
| Nikolai | Haddad | 0.59 |
| Leila | Okafor | 0.66 |
| Maya | Hassan | 0.92 |
| Priya | Lefèvre | 0.93 |
These six grades are real; the rule cannot forbid them. ALTER TABLE student ADD CONSTRAINT gpa_min CHECK (gpa >= 0);
Trying to add a NOT NULL column with no default to a table that has data:
OutputALTER TABLE student ADD COLUMN active BOOLEAN NOT NULL;
ERROR: column "active" of relation "student" contains null valuesBecause the existing rows get NULL for the new column, the rule is broken from the start. If there is a meaningful starting value for all rows, give a default in one step: ADD COLUMN active BOOLEAN NOT NULL DEFAULT TRUE. If the value differs from person to person, add the column first while allowing NULL, fill in the values, then run ALTER COLUMN active SET NOT NULL. Do not invent a fake default like '0000' just to silence the error; the missing information would then hide in the data.
ALTER TABLE changes a table without dropping it: it adds columns (ADD COLUMN), drops them (DROP COLUMN), renames them (RENAME COLUMN), and changes their type and properties (ALTER COLUMN ... TYPE / SET DEFAULT / SET NOT NULL); a rename breaks every query that uses the old name.DROP TABLE removes the table with its structure, and TRUNCATE deletes only the rows; neither can be done to a table that other tables reference. After a change becomes permanent (COMMIT), going back is possible only with a backup; in PostgreSQL these commands can be undone inside a transaction (BEGIN ... ROLLBACK), while in some database systems (MySQL, Oracle) table-structure commands are committed automatically.Next lesson: In unit 6 you designed and altered tables; in unit 7 we start writing rows into these tables with INSERT, and at the end of the unit you will build the event ticket system.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
gpaALTER TABLE course_offering ALTER COLUMN capacity TYPE SMALLINT; ALTER TABLE student ALTER COLUMN has_scholarship DROP DEFAULT; SELECT table_name, column_name, data_type, column_default FROM information_schema.columns WHERE (table_name = 'course_offering' AND column_name = 'capacity') OR (table_name = 'student' AND column_name = 'has_scholarship') ORDER BY table_name;
| table_name | column_name | data_type | column_default |
|---|---|---|---|
| course_offering | capacity | smallint | NULL |
| student | has_scholarship | boolean | NULL |
The type changed because all the capacities fit the SMALLINT limit. The default of has_scholarship was false and is now gone; since the column is still NOT NULL, a student can no longer be added without scholarship information.