Creating Tables in SQL: Using Create Table Command
Creating Tables in SQL: Using Create Table Command
BY – CHANDRANSHU JAIN
Introduction to CREATE TABLE
As learnt previously that we can create databases in sql . Now we know
that we need to store structured data(tables) in the created databases.
Using the CREATE TABLE command in sql we can easily create tables in
sql. A table comprises of rows and columns. Using the create table
command we inform sql the names of columns (features ) , their
datatype , etc. We can also enter some constraints on the columns to
restrict the type of data to be stored in the table and make data more
precise , accurate and reliable . Create table command is very helpful
especially when we have to test/try some query(s) .
Syntax of CREATE TABLE
create table table_name (
column 1_name type1(size) [constraint 1],
column 2_name type2(size) [constraint 2],
.
.
column n_name typen(size) [constraint n]);
Name Definition
table_name name of table
column i_name name of the ith column
typei type of data that is stored in the columns
size Size of the data we can store in column.
Example: if we enter int(10) , it means we want to
enter integer data type which can store maximum of
10 digits.
Constraint i Type of constraint on the ith column
Example :
create table customer (
cust_id int ,
cust_name varchar ,
phone_no int not null unique,
primary key(cust_id));
So we see here that the customer table has cust_id as primary key (non null and unique values) and the
orders table has order_id as primary key and the cust_id in orders table the foreign key (i.e. it links or
references to the customer table ) , so in this way the customer and orders table are related.
More Examples
create table employee (
id int ,
name varchar not null,
phone_number int unique,
age int check(age>=18) default 18,
primary key(id));