How to Create Table in SQL?
Let’s learn how to create table in SQL with the following example.
Table name will be ‘employee’, and this table comprises employee ID, employee name, employee salary, age, gender and the department in which the employee works
Step 1: Creating a table which involves naming the table
Step 2: Defining its columns which are part of the table
Step 3: Assigning a data type to each column
Syntax of create table in SQL with an example
CREATE TABLE tablename(
column1 datatype,
column2 datatype,
…
columnN datatype,
PRIMARY KEY(one or more columns));
where CREATE TABLE is the keyword, tablename is the name of the table name, columns1 to columnN are the set of columns, and PRIMARY KEY is a constraint followed by a semicolon
Let’s create an employee table
Create the table, employee(
e_id int not null,
e_name varchar(20),
e_salary int,
e_age int,
e_gender varchar(20),
e_dept varchar (20),
primary key(e_id)
);
- Not null is the constraint used to signify that all cells of this column must have a value
- Varchar stands for variable length character, and the value passed is the maximum length of the character
- Primary key constraints help uniquely identify all records from the table, and a table cannot have more than one primary key
- After writing the query, click on the execute button to check for errors
- Once the query is executed, a message appears like ‘Commands completed successfully’
How to Drop Table in SQL?
It is used to delete a table from the database.
Syntax of Drop Table in SQL with an example
DROP TABLE TableName;
where DROP TABLE is the keyword and tablename is the name of the table followed by a semicolon
- Now, let us see an example of dropping a table
DROP TABLE test;
- After writing the query, click on the execute button to check for errors
- Once the query is executed, a message appears like ‘Commands completed successfully’.
We have successfully created the employee table and had a quick brief on how to drop a table in SQL! In the next tutorial section, we will discuss on how to insert values into the table.