Skip to content

01 SQL ‐ Create Table

Pankaj Chouhan edited this page Sep 29, 2023 · 1 revision

To create a table in SQL, you can use the CREATE TABLE statement. This statement allows you to define the table's structure, including the column names, data types, constraints, and more. Here's the basic syntax for creating a table:

CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
    -- Additional columns go here
    CONSTRAINT constraint_name PRIMARY KEY (one_or_more_columns)
);

Let's break down the components of the CREATE TABLE statement:

  • table_name: This is the name of the table you want to create.
  • column1, column2, column3, etc.: These are the names of the columns within the table.
  • datatype: Specifies the data type for each column, indicating what kind of data the column can hold (e.g., INT for integers, VARCHAR(n) for variable-length character strings, DATE for dates).
  • CONSTRAINT constraint_name PRIMARY KEY: This part defines a primary key constraint for the table. The primary key uniquely identifies each row in the table and enforces data integrity.

Here's an example of creating a simple "students" table with a primary key:

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    date_of_birth DATE
);

In this example, we create a table named "students" with four columns: "student_id," "first_name," "last_name," and "date_of_birth." The "student_id" column is defined as the primary key.

You can customize your table's structure by adding more columns, specifying constraints like foreign keys or unique constraints, and defining default values or check constraints as needed.

Remember that the specific syntax and data types may vary depending on the SQL database management system you are using (e.g., MySQL, PostgreSQL, SQL Server), so consult your database system's documentation for details specific to your environment.

Clone this wiki locally