SQL CREATE TABLE



SQL CREATE TABLE Statement

The SQL CREATE TABLE statement is used to create a new table in a database. Tables are essential structures in a database that store data in rows and columns. Each table should have a unique name and define the columns that will store data.


Syntax

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ...
);
  • CREATE TABLE: This is the SQL keyword used to create a new table.
  • table_name: This specifies the name of the table you want to create.
  • column1, column2, column3, ...: These are the names of the columns in the table.
  • datatype: This specifies the type of data the column can hold, such as INTEGER, VARCHAR, DATE, etc.

Example

Let's go through a complete example that includes creating a database, creating a table, and displaying the table.

Step 1: Creating a Database

This step involves creating a new database where the table will be stored.

CREATE DATABASE example_db;

In this example, we create a database named example_db.

Step 2: Creating a Table

In this step, we create a table named employees within the previously created database.

USE example_db;

CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    email VARCHAR(100),
    hire_date DATE
);

Here, we define the employees table with columns for id, first_name, last_name, email, and hire_date. The id column is set as the primary key and will auto-increment.

Step 3: Displaying the Table

This step involves displaying the structure of the created table to verify its columns and data types.

DESCRIBE employees;

This command will show the structure of the employees table, including its columns and their data types.