How do you create a new table in SQL?
Posted by RoseHrs
Last Updated: July 21, 2024
To create a new table in SQL, you can use the CREATE TABLE statement. Below is the basic syntax for creating a table:
CREATE TABLE table_name (
    column1 datatype constraints,
    column2 datatype constraints,
    column3 datatype constraints,
    ...
);
Explanation:
- table_name: The name you want to assign to your new table. - column1, column2, etc.: The names of the columns that you want in your table. - datatype: The data type for each column (e.g., INT, VARCHAR(255), DATE, etc.). - constraints: Optional rules for the columns, such as PRIMARY KEY, NOT NULL, UNIQUE, etc.
Example:
Here's an example of creating a simple employees table:
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    hire_date DATE,
    salary DECIMAL(10, 2)
);
Explanation of the Example:
- employee_id: An integer that serves as the primary key for the table, meaning it must be unique for each row. - first_name and last_name: Variables that cannot be null (NOT NULL constraint). - hire_date: A date field to store when the employee was hired. - salary: A decimal value that allows for two digits after the decimal point. After executing the CREATE TABLE command, your new table will be created and ready for you to insert data into it.