Section outline

  • Topics Objective:

    1. Understand How to create DB, table and insert data.

    Topics Outcomes: 

    1. Able to create database.

    2.  Able to create table with proper primary and foreign key.

    3. Able to insert data.


    The SQL CREATE DATABASE Statement

    The CREATE DATABASE statement is used to create a new SQL database.

    Syntax

    CREATE DATABASE databasename;


    The SQL DROP DATABASE Statement

    The DROP DATABASE statement is used to drop an existing SQL database.

    Syntax

    DROP DATABASE databasename;


    SQL PRIMARY KEY on CREATE TABLE

    The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:

    Syntax

    CREATE TABLE Persons (
        ID int NOT NULL,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255),
        Age int,
        PRIMARY KEY (ID)
    );


    SQL FOREIGN KEY Constraint

    A FOREIGN KEY is a key used to link two tables together.

    A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.

    The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.

    Look at the following two tables:

    "Persons" table:

    Syntax

    CREATE TABLE Orders (
        OrderID int NOT NULL,
        OrderNumber int NOT NULL,
        PersonID int,
        PRIMARY KEY (OrderID),
        FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
    );


    • SQL ALTER TABLE Statement

      The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The ALTER TABLE statement is also used to add and drop various constraints on an existing table.

      This Alter belongs to followings: 

      • ADD Column
      • DROP COLUMN
      • ALTER/MODIFY COLUMN
      • Change Data Type