How to create a table

The syntax of the CREATE TABLE statement

      CREATE TABLE [IF NOT EXISTS] tableName 
                   ( columnName1 dataType [columnAttributes]
                   [, columnName2 dataType [columnAttributes]]
                   [, columnName3 dataType [columnAttributes]]... 
                   )
      

Three common column attributes

Attribute Description
UNIQUE Specifies that each value stored in the column must be unique, but allows the column to store NULL values.
NOT NULLL Indicates that the column doesn’t accept NULL values. If omitted, the column can accept NULL values.
DEFAULT default_value Specifies a default value for the column.

A table without column attributes

      CREATE TABLE customers ( 
        customerID INT,
        firstName VARCHAR(60),
        lastName VARCHAR(60)
      );
      

A table with column attributes

      CREATE TABLE customers (
        customerID INT NOT NULL UNIQUE,
        firstName VARCHAR(60) NOT NULL,
        lastName VARCHAR(60) NOT NULL
      );
      

Another table with column attributes

      CREATE TABLE orders (
        orderID  INT NOT NULL UNIQUE,
        customerID INT NOT NULL UNIQUE,
        orderNumber VARCHAR(50) NOT NULL,
        orderDate DATE NOT NULL,
        orderTotal DECIMAL(9,2) NOT NULL,
        paymentTotal DECIMAL(9,2) DEFAULT 0
      );
      

Description

Back