Creating a table

Previous Index Next

Syntax Examples Data types

In SQL, we use the command CREATE TABLE to create a table.

Syntax Top

CREATE TABLE <table_name>
(<field_name> <data_type> [NULL | NOT NULL]
{, <field_name> <data_type> [NULL | NOT NULL]})

This statement creates a table named <table_name> with fields listed in brackets. Each field name must be followed by the data type of the field. The null status (specified by the keywords NULL or NOT NULL) determines whether the field allows null values or not. If the null status is not specified, most systems will assume that the field allows null values.

Examples Top

Create a table called sample which has only one character field (id) of length 8.
CREATE TABLE sample (id char(8))
 
Create a table called s6a (the students in the class Secondary 6A) which has the following nine fields:
  • class_num (class number): This is an integer field which does not allow null values;
  • stud_id (student identity code): This is a character field (of length 5) which does not allow null values;
  • name: This is a character field (of length 30) which does not allow null values;
  • email (electronic mail address): This is a character field (of length 30) which allows null values;
  • clc, ue, phy, pm, cs (examination marks of five subjects): These are integer fields which allow null values.
CREATE TABLE s6a
(class_num integer NOT NULL,
  stud_id char(5) NOT NULL,
  name char(30) NOT NULL,
  email char(30) NULL,
  clc integer NULL,
  ue integer NULL,
  phy integer NULL,
  pm integer NULL,
  cs integer NULL)

Data types Top

The data types supported by different systems may be different, but most systems support the following data types:

Most systems require explicit lengths for char but not for numeric or date/time data types. For char, the length may be specified by enclosing the value of the length in brackets () following char.

If the length is not specified in the CREATE TABLE statement, the actual length of the field depends on the system used.

Previous Index Next