0% found this document useful (0 votes)
2 views17 pages

Lab Lecture Note 2 (SQL Database & Table)

The document provides a comprehensive overview of SQL commands for creating, managing, and deleting databases and tables. It covers the syntax and examples for 'CREATE DATABASE', 'DROP DATABASE', 'CREATE TABLE', 'INSERT INTO', and other related commands. Additionally, it explains the differences between various SQL operations like DELETE, TRUNCATE, and DROP, along with how to rename tables and copy data between them.

Uploaded by

tasriftanim2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views17 pages

Lab Lecture Note 2 (SQL Database & Table)

The document provides a comprehensive overview of SQL commands for creating, managing, and deleting databases and tables. It covers the syntax and examples for 'CREATE DATABASE', 'DROP DATABASE', 'CREATE TABLE', 'INSERT INTO', and other related commands. Additionally, it explains the differences between various SQL operations like DELETE, TRUNCATE, and DROP, along with how to rename tables and copy data between them.

Uploaded by

tasriftanim2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

SQL Create Database

In SQL, the 'Create Database' statement is a first step for storing the structured
data in the database. The database developers and the users use this statement in
SQL for creating the new database in the database systems. It creates the
database with the name which has been specified in the Create Database
statement. Syntax of Create Database statement in MySQL is:

CREATE DATABASE Database_Name;

In this syntax, Database_Name specifies the name of the database which we want
to create in the system. We have to type the database name in query just after the
'Create Database' keyword. Following are the most important points which are
required to learn while creating a database:

• The database we want to create should be a simple and unique name, which
can be easily identified.
• Database name should be no more than 128 characters.

Example 1: This example creates the Student database. To create the Student
database, you have to type the following command in Structured Query Language:
CREATE DATABASE Student;

When this query is executed successfully, then it will show the following output:

Database created successfully

You can also verify that your database is created in SQL or not by using the
following query:
SHOW DATABASES;

SQL does not allow developers to create the database with the existing database
name. Suppose if you want to create another Student database in the same
database system, then the Create Database statement will show the following error
in the output:

Can't create database 'Student'; database exists

So, firstly you have to delete the existing database by using the Drop Statement
before creating a same name database.

1|Page
You can also replace the existing database with the help of Replace keyword. If
you want to replace the existing Student database, then you have to type the
following SQL query:

CREATE OR REPLACE DATABASE Student;

Example 2: Suppose, we want to create the Employee database in the system.


Firstly, we have to type the following command in Structured Query Language:

CREATE DATABASE Employee;

When this query is executed successfully, then it will show the following output:

Database created successfully

You can also check that your database is created in SQL by typing the following
query:

SHOW DATABASES;

To replace the existing Employee database with a new Employee database, we


have to type the following query in SQL:

CREATE OR REPLACE DATABASE Employee;

SQL DROP Database


The SQL Drop Database statement deletes the existing database permanently from
the database system. This statement deletes all the views and tables if stored in the
database, so be careful while using this query in SQL. Following are the most
important points which are required to learn before removing the database from the
database system:
• This statement deletes all the data from the database. If you want to restore
the deleted data in the future, you should keep the backup of data of that
database which you want to delete.
• Another most important point is that you cannot delete that database from the
system which is currently in use by another database user. If you do so,
then the drop statement shows the following error on screen:

Cannot drop database "name_of_the_database" because it is currently in use.

2|Page
Syntax of Drop Database Statement in MySQL is:

DROP DATABASE Database_Name;

In this SQL syntax, we have to specify the name of that database which we want
to delete permanently from the database system.

Example1: Suppose, we want to delete the Student database with all its data from
the database system. Firstly, we have to check that the Student database exists in
the system or not by using the following statement:

SHOW DATABASES;

If the Student database is shown in the output, then we have to type the following
query in SQL for removing the Student database:

DROP DATABASE Student;

If the Student database does not exist in the database system and we run the above
query in SQL, then the query will show the following output:

Can't drop database 'Student'; database doesn't exist

SQL DROP DATABASE IF EXISTS Statement

The SQL DROP DATABASE IF EXISTS statement includes a condition to check


whether the database exists before trying to delete it. If the database does not
exist in the database system, the "DROP DATABASE IF EXISTS" statement does
not raise an error, but it simply terminates without taking any action.

Following is the syntax of the DROP DATABASE IF EXISTS statement.

DROP DATABASE IF EXISTS DatabaseName;

Here, the DatabaseName is the name of the database that you want to delete.

Example: Let us try to delete an existing database student in the database system
using the following SQL statement:

DROP DATABASE IF EXISTS student;

3|Page
When we execute the above SQL statement, the output is obtained as follows:

Query OK, 0 rows affected, 3 warnings (0.024 sec)

Now, let us try again to delete the database student that doesn't exist in the
database system using the following SQL statement:

DROP DATABASE IF EXISTS student;

When we execute the above SQL statement, the output is obtained as follows:

Query OK, 0 rows affected, 1 warning (0.000 sec)

SQL SELECT Database (USE Keyword)


Suppose database users and administrators want to perform some operations on
tables, views, and indexes on the specific existing database in SQL. Firstly, they
have to select the database on which they want to run the database queries. Any
database user and administrator can easily select the particular database from the
current database server using the USE statement in SQL.

Syntax of USE statement in MySQL

USE database_name;

Example 1: Suppose, you want to work with the Hospital database. For this firstly,
you have to check that if the Hospital database exists on the current database
server or not by using the following query:

SHOW DATABASES;

If the Hospital database is shown in the output, then you have to execute the
following query to select the Hospital database:

USE Hospital;

Example 2: Suppose, you want to work with another College database in SQL. For
this firstly, you have to check that the College database exists on the current
database server or not by using the following query:

4|Page
SHOW DATABASES;

If the College database is shown in the result, then you have to execute the
following query to select the College database:

USE College;

SQL Table

• Table is a collection of data, organized in terms of rows and columns. In


DBMS term, table is known as relation and row as tuple.
• Table is the simple form of data storage. A table is also considered as a
convenient representation of relations.
• A table has a specified number of columns, but can have any number of
rows.

Let's see an Example of an Employee table.


Employee

EMP_NAME ADDRESS SALARY


Ankit Lucknow 15000

Raman Allahabad 18000

Mike New York 20000

In the above table, "Employee" is the table name, "EMP_NAME", "ADDRESS"


and "SALARY" are the column names. The combination of data of multiple
columns forms a row e.g. "Ankit", "Lucknow" and 15000 are the data of one
row.

SQL CREATE TABLE


SQL CREATE TABLE statement is used to create table in a database. If you want
to create a table, you should name the table and define its column and each
column's data type.

5|Page
Let's see the simple syntax to create the table.

CREATE TABLE "tablename"


("column1" "data type",
"column2" "data type",
"column3" "data type",
...
"columnN" "data type");

The data type of the columns may vary from one database to another. For
example, NUMBER is supported in Oracle database for integer value whereas INT
is supported in MySQL.

Example 01: Let us take an example to create a STUDENTS table with ID as


primary key and NOT NULL are the constraint showing that these fields cannot
be NULL while creating records in the table.

CREATE TABLE STUDENTS (


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
PRIMARY KEY (ID)
);

You can verify it, if you have created the table successfully by using DESC
command as follows:

DESC STUDENTS;
The output will be:
FIELD TYPE NULL KEY DEFAULT EXTRA

ID Int(11) NO PRI

NAME Varchar(20) NO

AGE Int(11) NO

ADDRESS Varchar(25) YES NULL

4 rows in set (0.00 sec)

6|Page
Now you have the STUDENTS table available in your database and you can use to
store required information related to students.

Example 02: Let's see the command to create an Employee table in MySQL
database.

CREATE TABLE Employee


(
Employee_ID int,
First_Name varchar(255),
Last_Name varchar(255),
Email varchar(255),
Address_Line varchar(255),
City varchar(255)
);

You can verify it, if you have created the table successfully by using DESC
command as follows:

DESC STUDENTS;
The output will be:

Create a Table using Another Table

• We can create a copy of an existing table using the CREATE TABLE


command.
• The new table gets the same column signature as the old table. •
We can select all columns or some specific columns.
• If we create a new table using an old table, the new table will be filled with
the existing value from the old table.

7|Page
The basic syntax for creating a table with the other table is:

CREATE TABLE table_name AS


SELECT column1, column2,...
FROM old_table_name WHERE ..... ;

Example 01: The following SQL creates a copy of the employee table including
all columns.

CREATE TABLE EmployeeCopy AS


SELECT *
FROM Employee;

You can verify it, if you have created the table successfully by using DESC
command as follows:

DESC EmployeeCopy;

Example 02: The following SQL creates a copy of the employee table including
some columns.

CREATE TABLE EmployeeCopy2 AS


SELECT Employee_ID, First_Name, Email
FROM Employee;

You can verify it, if you have created the table successfully by using DESC
command as follows:

DESC EmployeeCopy2;

SQL INSERT INTO Statement


This SQL statement inserts the data or records in the existing table of the SQL
database. This statement can easily insert single and multiple records in a single
query statement.

Insert a Single Record

The Syntax of insert a single record is given below.

8|Page
INSERT INTO table_name
(
column_name1, column_name2, .…, column_nameN)
VALUES
(value_1, value_2, ..…, value_N);

Example of insert a single record:

INSERT INTO employee


(Employee_ID, First_Name, Last_Name, Email, Address_Line, City)
VALUES
(101, 'Ishtiaq', 'Ahammad', '[email protected]', 'Airport', 'Dhaka');

Make sure to use single quotation marks around the string values (e.g., 'Ishtiaq',
'Ahammad', '[email protected]', 'Airport', 'Dhaka').

Insert Multiple Records

The Syntax of insert multiple records in a single query is given below.

INSERT INTO table_name


(column_name1, column_name2, .…, column_nameN)
VALUES (value_1, value_2, ..…, value_N), (value_1, value_2, ..…, value_N),
….;

Example of inserting multiple records in a single query:

INSERT INTO employee


(Employee_ID, First_Name, Last_Name, Email, Address_Line, City)
VALUES
(102, 'A', 'B', '[email protected]', 'Airport', 'Dhaka'),
(103, 'C', 'D', '[email protected]', 'Mirpur', 'Dhaka'),
(104, 'E', 'F', '[email protected]', 'Mirpur', 'Dhaka'),
(105, 'G', 'H', '[email protected]', 'Sadar', 'Netrokona');

9|Page
SQL DROP TABLE

• A SQL DROP TABLE statement is used to delete a table definition and all
data from a table.
• This is very important to know that once a table is deleted all the information
available in the table is lost forever, so we have to be very careful when
using this command.

Let's see the syntax to drop the table from the database.

DROP TABLE "table_name";

Example 01: First, we verify STUDENTS table and then we would delete it from
the database.

DESC STUDENTS;
FIELD TYPE NULL KEY DEFAULT EXTRA

ID Int(11) NO PRI

NAME Varchar(20) NO

AGE Int(11) NO

ADDRESS Varchar(25) YES NULL

4 rows in set (0.00 sec)

This shows that STUDENTS table is available in the database, so we can drop it
as follows:

DROP TABLE STUDENTS;

Now, use the following command to check whether table exists or not.

DESC STUDENTS;

Query OK, 0 rows affected (0.01 sec)

As you can see, table is dropped so it doesn't display it.

10 | P a g e
SQL DELETE TABLE

The DELETE statement is used to delete rows from a table. If you want to
remove a specific row from a table you should use WHERE condition. The
Syntax for this is:

DELETE FROM table_name WHERE condition;

You can combine N number of conditions using AND or OR operators. But if


you do not specify the WHERE condition it will remove all the rows from the
table. The Syntax for this is:

DELETE FROM table_name;

Example 01: Let us consider, we want to Delete a single record from our employee
table. Then the query will be:

DELETE FROM employee


WHERE City = 'Netrokona';

Example 02: Let us consider, we want to Delete multiple record including


multiple condition from our employee table. Then the query will be:

DELETE FROM employee


WHERE Address_Line = 'Mirpur' AND Employee_ID = 103;

Example 03: Let us consider, we want to Delete all rows from our employee table.
Then the query will be:

DELETE FROM employee;

Difference Between DELETE and TRUNCATE Statements


There is a slight difference b/w delete and truncate statement. The DELETE
statement only deletes the rows from the table based on the condition defined by
WHERE clause or delete all the rows from the table when condition is not specified.
But it does not free the space containing by the table.

The TRUNCATE statement is used to delete all the rows from the table and free
the containing space.

11 | P a g e
The Example Syntax for truncate a table is:

TRUNCATE TABLE employee;

Truncate table is faster and uses lesser resources than DELETE TABLE
command.

Difference Between DROP and TRUNCATE Statements

When you use the drop statement it deletes the table's row together with the
table's definition so all the relationships of that table with other tables will no
longer be valid.

When you drop a table:


• Table structure will be dropped

• Relationship will be dropped

• Integrity constraints will be dropped

• Access privileges will also be dropped

On the other hand, when we TRUNCATE a table, the table structure remains the
same, so you will not face any of the above problems. Drop table command delete
complete table along with table structure too. TRUNCATE TABLE doesn't
delete the structure of the table.

SQL RENAME TABLE


In some situations, database administrators and users want to change the name of
the table in the SQL database because they want to give a more relevant name to
the table.
Any database user can easily change the name by using the ALTER TABLE
statement in MySQL Language.

Syntax of ALTER TABLE statement in MySQL

ALTER TABLE old_table_name RENAME TO new_table_name;

Example 1: Suppose, you want to change the name of the “employeecopy” using
ALTER TABLE statement. For this, you have to type the following query in SQL.

ALTER TABLE employeecopy RENAME TO Employee_Details;

12 | P a g e
After this statement, the table "employeecopy" will be changed into the table
name "Bikes_Details".

Example 2: Suppose, you want to change the name of the “studentscopy” using
ALTER TABLE statement. For this, you have to type the following query in SQL.

ALTER TABLE studentscopy RENAME TO Students_Details;

After this statement, the table "studentscopy" will be changed into the table name
"Students_Details".

SQL COPY DATA FROM TABLE

• If you want to copy the data (row value) of one SQL table into another SQL
table in the same MySQL server, then it is possible by using the INSERT
INTO statement in SQL.
• The INSERT INTO statement in SQL copies the content from one existing
table into the new table.
• But you have to remember that the tables should have the same name and
same number of attributes (i.e., columns).

Syntax of Copy Data from Another Table in MySQL

INSERT INTO New_table_name


SELECT * FROM old_table_name;

Example 1: Suppose, you want to insert data into the “employeecopy” table from
“employee” table using INSERT INTO statement. For this, you have to type the
following query in SQL.

INSERT INTO employeecopy


SELECT * FROM employee;

Example 2: Suppose, you want to insert data into the “studentscopy” table from
“students” table using INSERT INTO statement. For this, you have to type the
following query in SQL.

INSERT INTO studentscopy


SELECT * FROM students;

13 | P a g e
Copy Data from Another Table with WHERE Clause

Example 1: Suppose, you want to insert data only some row data (not all) into
the “employeecopy” table from “employee” table using INSERT INTO statement.
For this, you have to type the following query in SQL.

INSERT INTO employeecopy


SELECT * FROM employee WHERE Employee_ID = 103;

This query will insert only one row data into the “employeecopy” table from
“employee” table.

Example 2: Suppose, you want to insert data only some row data (not all) into
the “employeecopy” table from “employee” table using INSERT INTO statement.
For this, you have to type the following query in SQL.

INSERT INTO employeecopy


SELECT * FROM employee
WHERE Employee_ID = 104 OR Employee_ID = 105;

This query will insert two rows of data into the “employeecopy” table from
“employee” table.

SQL ALTER TABLE


The ALTER TABLE statement in Structured Query Language allows you to add,
modify, and delete columns of an existing table. This statement also allows
database users to add and remove various SQL constraints on the existing tables.
Any user can also change the name of the table using this statement.

ALTER TABLE ADD Column Statement


In many situations, you may require to add the columns in the existing table.
Instead of creating a whole table or database again you can easily add single and
multiple columns using the ADD keyword.

Syntax of ALTER TABLE ADD Column Statement in SQL ALTER

TABLE table_name ADD column_name column-definition;

14 | P a g e
The above syntax only allows you to add a single column to the existing table. If
you want to add more than one column to the table in a single SQL statement,
then use the following syntax.

ALTER TABLE table_name


ADD (column_Name1 column-definition,
column_Name2 column-definition,
.....
column_NameN column-definition);

Examples of ALTER TABLE ADD Column statement in SQL

Example 1: Let's take an example of a table named EmployeeCopy2. Suppose, you


want to add two columns, Last_Name and City, in the above Employeecopy2 table.
For this, you have to type the following query in the SQL.

ALTER TABLE employeecopy2 ADD (Last_Name Varchar(13), City varchar(50));

This statement will add Last_Name and City columns to the Employee table.

ALTER TABLE MODIFY Column Statement in SQL

The MODIFY keyword is used for changing the column definition of the existing
table.

Syntax of ALTER TABLE MODIFY Column statement in SQL ALTER

TABLE table_name MODIFY column_name column-definition;

This syntax only allows you to modify a single column of the existing table. If you
want to modify more than one column of the table in a single SQL statement, then
use the following syntax.

ALTER TABLE table_name


MODIFY column_name1 column_definition, MODIFY column_name2 colum_
definition,
.....
MODIFY column_name_n column-definition;

15 | P a g e
Examples of ALTER TABLE MODIFY Column statement in SQL

Example 1: Let's take an example of a table named EmployeeCopy2. Suppose, you


want to Modify two columns, Last_Name and City, in the above Employeecopy2
table. We want to change their data type from Varchar to char. For this, you
have to type the following query in the SQL.

ALTER TABLE employeecopy2 MODIFY Last_Name char(13), MODIFY City


char(50);

This statement will Modify Last_Name and City columns to the Employee table.

ALTER TABLE DROP Column Statement in SQL

In many situations, you may require to delete the columns from the existing table.
Instead of deleting the whole table or database you can use DROP keyword for
deleting the columns. To delete multiple columns, you have to write separate
command for each column.

Syntax of ALTER TABLE DROP Column statement in SQL

ALTER TABLE table_name DROP Column column_name;

Examples of ALTER TABLE DROP Column statement in SQL

Example 1: Suppose, you want to delete the Last_Name and City column from
the above Employeecopy2 table. For this, you have to type the following two
different queries in the SQL.

ALTER TABLE employeecopy2 DROP COLUMN Last_Name;


ALTER TABLE employeecopy2 DROP COLUMN City;

ALTER TABLE CHANGE Column Name Statement in SQL


The CHANGE keyword is used for changing the name of columns or fields of the
existing table.

Syntax of ALTER TABLE CHANGE Column Name statement in SQL ALTER

TABLE table_name CHANGE old_name new_name data_definition;

16 | P a g e
Examples of ALTER TABLE CHANGE Column Name statement in SQL

Example 1: Let's take an example of a table named Employeecopy2. Suppose, you


want to change the name of the First_Name column to Last_Name column of
the above Employeecopy2 table. For this, you have to type the following query in
the SQL.

ALTER TABLE employeecopy2 CHANGE First_Name Last_Name


VARCHAR(255);

This statement will change the name of the First_Name column to Last_Name.

17 | P a g e

You might also like