100 Days of SQL

sql

Day 31 – SQL CREATE TABLE

SQL CREATE TABLE statement is used to create a new table in a database. The syntax for the CREATE TABLE statement is as follows:


CREATE TABLE table_name (
   column1 datatype [NULL | NOT NULL],
   column2 datatype [NULL | NOT NULL],
   ...
   columnN datatype [NULL | NOT NULL]
);

In this syntax, “table_name” is the name of the new table that you want to create, and “column1” through “columnN” are the names of the columns in the table.

Here’s an example of how to create a new table named “employees” with three columns: “id”, “name”, and “salary”:


CREATE TABLE employees (
   id INT NOT NULL,
   name VARCHAR(50) NOT NULL,
   salary DECIMAL(10, 2) NOT NULL
);

When this statement is executed, SQL Server will create a new table named “employees” with three columns: “id” of data type INT, “name” of data type VARCHAR(50), and “salary” of data type DECIMAL(10, 2).

You can also specify additional constraints on the columns, such as PRIMARY KEY, UNIQUE, and FOREIGN KEY constraints. Here’s an example that shows some additional constraints:


CREATE TABLE employees (
   id INT NOT NULL PRIMARY KEY,
   name VARCHAR(50) NOT NULL,
   salary DECIMAL(10, 2) NOT NULL,
   department_id INT NOT NULL FOREIGN KEY REFERENCES departments(id)
);

In this example, we add a PRIMARY KEY constraint on the “id” column and a FOREIGN KEY constraint on the “department_id” column that references the “id” column in the “departments” table.