CREATE TABLE adds a new table to a database. You name the table, then list its columns, giving each one a name and a data type that says what kind of value it holds.
CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype);An example
Section titled “An example”The production company wants to record the filming locations it hires. A table for them:
CREATE TABLE Locations ( LocationID int, ProductionID int, Name varchar(100), Town varchar(100), DailyFee decimal(10, 2), FirstShootDay date);Each column’s type sets what it can hold:
intholds whole numbers: the IDs.varchar(100)holds text of up to 100 characters: the name and town.decimal(10, 2)holds exact numbers with two decimal places, which suits money.dateholds a calendar date.
The table starts empty, with its columns ready:
| LocationID | ProductionID | Name | Town | DailyFee | FirstShootDay |
|---|---|---|---|---|---|
INSERT INTO fills it, and SQL Data Types lists the types each database offers.
Rules on the columns
Section titled “Rules on the columns”A real table usually needs rules as well as types: an ID that must be unique, a name that must not be empty, a production that must exist. These rules are called constraints, and are written into CREATE TABLE too. SQL Constraints covers them.
A table from a query
Section titled “A table from a query”CREATE TABLE … AS creates a table and fills it from a query in one step. The new table takes its columns from the query:
CREATE TABLE UKProductions ASSELECT Title, BudgetFROM ProductionsWHERE Country = 'UK';| Title | Budget |
|---|---|
| The Lantern Keepers | 18,500,000 |
| Quarry Lane | 7,200,000 |
| Six Bells | 11,000,000 |
SQL Server and Microsoft Access write this as SELECT INTO instead.