SQL Tutorial
Creating a new table in SQL involves using the CREATE TABLE
statement, followed by the table name and a list of columns with their corresponding data types and optional constraints.
Here is the basic syntax:
CREATE TABLE table_name ( column1 datatype constraint, column2 datatype constraint, column3 datatype constraint, .... );
Each column in the table is separated by a comma, and the whole list of columns is enclosed in parentheses.
For example, let's say we want to create a table named Employees
with the columns ID
, FirstName
, LastName
, and Email
. The ID
will be of integer type and we will use it as the primary key. The rest of the columns will be of varying character (VARCHAR
) type with a maximum length of 255 characters. Here is how you can do it:
CREATE TABLE Employees ( ID int PRIMARY KEY, FirstName varchar(255), LastName varchar(255), Email varchar(255) );
In this example, PRIMARY KEY
is a constraint that indicates that the ID
column is the primary key of the table.
Please note that the exact SQL syntax can differ between various SQL databases. For example, some databases require you to explicitly specify if a column can be NULL
or must be NOT NULL
. Always consult the documentation for the specific database management system (DBMS) you are using.
Creating a Table in SQL:
CREATE TABLE TableName ( Column1 datatype, Column2 datatype, ... );
Specifying Columns in CREATE TABLE Statement:
CREATE TABLE Employees ( EmployeeID INT, FirstName VARCHAR(50), LastName VARCHAR(50), Salary DECIMAL(10,2) );
SQL CREATE TABLE with Primary Key:
CREATE TABLE Students ( StudentID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50) );
Defining Data Types in CREATE TABLE:
CREATE TABLE Products ( ProductID INT, ProductName VARCHAR(100), Price DECIMAL(8,2), InStock BOOLEAN );
Adding Constraints in SQL CREATE TABLE:
CREATE TABLE Orders ( OrderID INT, CustomerID INT, OrderDate DATE, CONSTRAINT PK_Orders PRIMARY KEY (OrderID), CONSTRAINT FK_CustomerID FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) );
Setting Default Values in CREATE TABLE:
CREATE TABLE Tasks ( TaskID INT, TaskName VARCHAR(50) DEFAULT 'DefaultTask', DueDate DATE DEFAULT GETDATE() );
Creating Indexes with SQL CREATE TABLE:
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), INDEX IX_LastName (LastName) );