Try an online SQL class for free!
Additional Resources

Creating and Modifying Tables

In this lesson of the SQL tutorial, you will learn...
  1. To understand the different standard data types available in database tables.
  2. To create tables using CREATE TABLE.
  3. To modify existing table structures using ALTER TABLE.
  4. To delete tables using DROP TABLE.

At its most basic, creating tables involves specifying the name of the table, the fields the table contains and the data types of those fields. First, we'll take a look at data types and then we'll look at the syntax for creating, modifying and deleting tables.

Data Types

All major relational database management systems allow DBAs to specify the type of data a field can contain. The table below shows the most commonly used data types specified in ANSI SQL.

ANSI SQL Data Types
Data Type Description
Character A specific number of one-byte characters.
Character varying Up to a specific number of one-byte characters.
National character A specific number of two-byte characters.
National character varying Up to a specific number of two-byte characters.
Integer A whole number between -2^32 and +2^32 (2,147,483,648).
Smallint A whole number between -2^15 and +2^15 (32,768).
Decimal A floating-point number between -10^38+1 and 10^38+1.
Real An extremely large positive or negative floating-point number often stored using scientific notation with the potential for some relatively small loss of accuracy.
Date A date.
Time A time.

Unfortunately, different RDBMSs use different terms for these data types. The terms for SQL Server, Oracle and MySQL are shown below. You'll notice that there is some variation.

ANSI SQL Data Types
Data type SQL Server Oracle MySQL
Character char(n) (see footnote) char(n) char(n)
Character varying varchar(n) varchar(n) varchar(n)
National character nchar(n) char(n) nchar(n)
National character varying nvarchar(n) varchar(n) nvarchar(n)
Integer int int int
Smallint smallint smallint smallint
Decimal decimal(n1,n2) (see footnote) decimal(n1,n2) decimal(n1,n2)
Real real real real
Date datetime date date
Time datetime date time

Creating Tables

Now that you understand data types, you're ready to learn how to create a table. Note that you must have the proper database permissions to do so.

Syntax
CREATE TABLE table_name
(
 column_name data_type,
 column_name data_type,
 column_name data_type,
 more columns...
)

NULL Values

As we have discussed, in some cases a value may not be set for a specific field in a specific record. In this case, that field contains NULL. In the CREATE TABLE statement, the default for each column is to allow for null values. This can be stated explicitly with the NULL flag or it can be changed with the NOT NULL flag.

Syntax
CREATE TABLE table_name
(
 column_name data_type NOT NULL,
 column_name data_type NULL,
 column_name data_type NOT NULL,
 more columns...
)

Primary Keys

Every table should have a primary key, which is a field or group of fields that can be used to uniquely identify specific records in the table. Primary keys can be specified in two ways as shown below.

Syntax
CREATE TABLE table_name
(
 column_name data_type PRIMARY KEY,
 column_name data_type null,
 column_name data_type not null,
 more columns...
)
Syntax
CREATE TABLE table_name
(
 column_name_pk data_type,
 column_name data_type null,
 column_name data_type not null,
 more columns...,
 CONSTRAINT PK_table_name PRIMARY KEY (column_name_pk)
)

When a table uses a group of fields for the primary key, the key is called a composite primary key. In this case, you must specify the primary key at the end of the CREATE TABLE statement as shown below.

Syntax
CREATE TABLE table_name
(
 column_name_pk1 data_type,
 column_name_pk2 data_type,
 column_name data_type not null,
 more columns...,
 CONSTRAINT PK_table_name PRIMARY KEY (column_name_pk1,column_name_pk2)
)

Foreign Keys

Foreign keys reference the primary key of another table, thereby creating a relationship between those two tables. They can be specified using the two methods shown below.

Syntax
CREATE TABLE table_name
(
 column_name data_type PRIMARY KEY,
 column_name data_type null,
 column_name_fk data_type FOREIGN KEY REFERENCES table2_name(column_name_pk),
 more columns...
)
Syntax
CREATE TABLE table_name
(
 column_name data_type PRIMARY KEY,
 column_name data_type null,
 column_name_fk data_type,
 more columns...,
 CONSTRAINT FK_table_name FOREIGN KEY REFERENCES table2_name(column_name_pk)
)

The code samples below show how to create duplicates of the Employees, Customers and Orders tables.

Code Sample: Tables/Demos/CreateTable.sql

CREATE TABLE Employees2
(
 EmployeeID int NOT NULL PRIMARY KEY,
 LastName nvarchar(20) NOT NULL,
 FirstName nvarchar(10) NOT NULL,
 Title nvarchar(30) NULL,
 TitleOfCourtesy nvarchar(25) NULL,
 BirthDate datetime NULL,
 HireDate datetime NULL,
 Address nvarchar(60) NULL,
 City nvarchar(15) NULL,
 Region nvarchar(15) NULL,
 PostalCode nvarchar(10) NULL,
 Country nvarchar(15) NULL,
 HomePhone nvarchar(24) NULL,
 Extension nvarchar(4) NULL,
 ReportsTo int FOREIGN KEY REFERENCES Employees(EmployeeID)
)

CREATE TABLE Customers2
(
 CustomerID nchar(5) PRIMARY KEY,
 CompanyName nvarchar(40) NOT NULL,
 ContactName nvarchar(30) NULL,
 ContactTitle nvarchar(30) NULL,
 Address nvarchar(60) NULL,
 City nvarchar(15) NULL,
 Region nvarchar(15) NULL,
 PostalCode nvarchar(10) NULL,
 Country nvarchar(15) NULL,
 Phone nvarchar(24) NULL,
 Fax nvarchar(24) NULL
)

CREATE TABLE Orders2
(
 OrderID int PRIMARY KEY,
 CustomerID nchar(5) FOREIGN KEY REFERENCES Customers2(CustomerID),
 EmployeeID int FOREIGN KEY REFERENCES Employees2(EmployeeID),
 OrderDate datetime NULL,
 RequiredDate datetime NULL,
 ShippedDate datetime NULL,
 ShipVia int NULL,
 Freight decimal(8,2) NULL
)
Code Explanation

Notice that all three tables have primary keys and that the Orders2 table has two foreign keys referencing the other two tables.

This demo uses SQL Server data types.

Exercise: Creating Tables

Duration: 30 to 40 minutes.

In this exercise you will create duplicates of the Products, Categories and Suppliers tables in the Northwind database.

  1. Open a new query window and write the three CREATE TABLE queries to create Products2, Categories2 and Suppliers2. Note that order matters and the order shown below is not correct. Set data types as you see appropriate.
    • Products2 with the following fields:
      • ProductID
      • ProductName
      • SupplierID
      • CategoryID
      • QuantityPerUnit
      • UnitPrice
      • UnitsInStock
      • UnitsOnOrder
      • ReorderLevel
    • Categories2 with the following fields:
      • CategoryID
      • CategoryName
    • Suppliers2 with the following fields:
      • SupplierID
      • CompanyName
      • ContactName
      • ContactTitle
      • Address
      • City
      • Region
      • PostalCode
      • Country
      • Phone
      • Fax
  2. Run the query to see if it executes. You can test it by select rows from your new tables. Of course, they won't have any, but you shouldn't get an error.

Adding and Dropping Columns

The syntax for adding a column to a table is shown below:

Syntax
ALTER TABLE table_name
ADD column_name data_type

Note that you will either have to allow for NULL values or set a default value for the new column.

The syntax for dropping a column to a table is shown below:

Syntax
ALTER TABLE table_name
DROP COLUMN column_name

Note that you cannot drop primary key columns.

Renaming Tables

The syntax for renaming tables is different in different RDBMSs.

SQL Server

SQL Server uses a built-in stored procedure for renaming tables:

Syntax
sp_rename table_name, new_table_name

Oracle and MySQL

Oracle and MySQL use the RENAME command for renaming tables:

Syntax
RENAME table_name TO new_table_name

Dropping Tables

Dropping tables is scarily easy; however, there are data integrity checks to make sure you don't drop tables that are referenced by other tables.

Syntax
DROP TABLE table_name

Creating and Modifying Tables Conclusion

In this lesson of the SQL tutorial, you have learned how to create and modify table structures, how to set data types and how to create relationships between tables using primary and foreign keys.

Footnotes

  1. n = number of characters

  2. n1 = total number of digits; n2 = number of digits allowed after the decimal point

To continue to learn SQL go to the top of this page and click on the next lesson in this SQL Tutorial's Table of Contents.
Last updated on 2009-05-11

Use of http://www.learn-sql-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm