Use Create Statement to Create Table in SQL Server - SQL Server / T- SQL Tutorial Part 34

Scenario:

An Excel file is provided to you with some information related to Customer with below columns
First Name,
Last Name,
Age,
Phone Number,
Data of Birth,
Sex

and you are asked to create Table in SQL Server Database and save the data in newly created Table.

Solution:

We can use create statement to create Table in SQL Server Database. Below is Create Statement


Create Table Table_Name
(
Column_OneName DataType(Size if required),
Column_TwoName DataType(Size if required),
Column_ThreeName DataType(Size if required),
Column_FourName DataType(Size if required)
)

If we would like to create table with our above requirement, our Create Statement with be

Create Table Customer
(FirstName VARCHAR(50),
LastName VARCHAR(50),
Age SmallInt,
PhoneNumber CHAR(9),
DOB Date,
Sex CHAR(1)
)

There are few points to notice in above Create Statement. I have not used the Schema Name with Table Name. If you would not provide Schema Name with Table Name, it will be created with dbo schema.

Let's say if we have Sales Schema and we would like to create Customer in Sales Schema. Our Create Statement will be


Create Table Sales.Customer
(FirstName VARCHAR(50),
LastName VARCHAR(50),
Age TinyInt,
PhoneNumber CHAR(9),
DOB Date,
Sex CHAR(1)
)

VARCHAR(50) for First Name and Last Name : It will let us store characters and the max number will be 50.
TinyInt for Age: It will let us store integer value between 0 to 255.
CHAR(9) for PhoneNumber : Char will let us store characters, as we know that we need to store 9 Characters, we used Char(9).
Date for DOB: In Date of Birth column, we will be able to store date as we have data type= date.
Char(1) for Sex: As we would like to store M or F for Sex, Char is going to let us store single character.


Video Demo : How to use Create Statement to create SQL Server Table 

1 comment: