Sample Video Frame
Exercise 12: Destroying And Altering Tables
You've already encountered DROP TABLE as a way to get rid of a table you've created. I'm going to show you another way to use it and also how to add or remove columns from a table with ALTER TABLE.
View Source file ex12.sql Only
/* Only drop table if it exists. */
DROP TABLE IF EXISTS person;
/* Create again to work with it. */
CREATE TABLE person (
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT,
age INTEGER
);
/* Rename the table to peoples. */
ALTER TABLE person RENAME TO peoples;
/* Add a hatred column to peoples. */
ALTER TABLE peoples ADD COLUMN hatred INTEGER;
/* Rename peoples back to person. */
ALTER TABLE peoples RENAME TO person;
.schema person
/* We don't need that. */
DROP TABLE person;
I'm doing some fake changes to the tables to demonstrate the commands, but this is everything you can do in SQLite3 with the ALTER TABLE and DROP TABLE statements. I'll walk through this so you understand what's going on:
ex21.sql:2: Use the
IF EXISTSmodifier and the table will be dropped only if it's already there. This suppresses the error you get when running your.sqlscript on a fresh database that has no tables.ex21.sql:5: Just recreating the table again to work with it.
ex21.sql:13: Using
ALTER TABLEto rename it topeoples.ex21.sql:16: Add a new column
hatredthat is anINTEGERto the newly renamed tablepeoples.ex21.sql:19: Rename
peoplesback topersonbecause that's a dumb name for a table.ex21.sql:21: Dump the schema for
personso you can see it has the newhatredcolumn.ex21.sql:24: Drop the table to clean up after this exercise.
Register for Learn SQL the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.