SQL
SQL
1. BASICS OF DBMS.
Database: database is collection of data in a format, that can be easily accessed.
Database Management System: DBMS is a software application that are used to manage our Data Bases.
Types of DBMS: There are usually two types of DBMS. These are Relational DBMS & Non-Relational DBMS. In
case of Relational database, all the data are stored in form of tables. Similarly, Non-Relational databases are not stored
in forms of table. These databases are also known as Non-SQL databases. Relational databases are also known as
SQL databases or RDBMS (Relational Database Management System). Example of Relational Database are: MySQL,
Oracle, Microsoft SQL server. Example of Non-Relational Database is: MongoDB.
SQL: This stands for Structured Query Language. This is a programming language used to interact with relational
databases. It is used to perform Create, Read, Update and Delete databases.
Database: These are the collection of inter-related data. Only and only data that are connected or related are stored
in database.
Creating our first database: to continue with SQL, we would first require a database. The codes to create a database
is “CREATE DATABASE” or “create database”. And it is written as follows:
CREATE DATABASE student;
Here, student is the name of the database. Similarly, an existing database can also be deleted by writing the code
“DROP DATABASE” or “drop database”. The code is generally written as:
DROP DATABASE student;
Here, the code DROP DATABASE is used to delete an existing database.
Creating our first table: After creating a database, its important to create tables with inter-related data. The code to
insert a table is: “CREATE TABLE”. And the code is written as:
CREATE TABLE student_list;
Here, student_list is the name of the table. After that its important to define the columns/schemas of the database. For
that the codes are written as follows:
CREATE TABLE student_list (
column_name1 datatype constraint,
column_name2 datatype constraint,
column_name3 datatype constraint
);
Here, column_name1, column_name2, column_name3 indicates the name of the column. For example: for the list of
students in a college, column_name1 would be the “registration_id”, column_name2 would be the “name” and
column_name3 would be the “age”. So the code becomes:
CREATE TABLE student_list (
Registration_id INT PRIMARY KEY,
name VARCHAR(50),
age INT NOT NULL
);
Here, INT stands for integer and denotes that the registration_id can only have numbers as their input. Similarly,
VARCHAR stands for variable character and it denotes that the input can only be alphabets (A-Z and a-z) and (50)
indicates the maximum character limit of the input. NOT NULL indicates that the value cannot be empty.
Inserting data to database table: After creating table in our database, its important to insert data to our table. The
code to insert data to our table are:
INSERT INTO student_list VALUES(1, “subhomoy”, 23);
INSERT INTO student_list VALUES(2, “sohom”, 23);
Here, VALUES indicate the code to insert data to the table and all the data can be entered by using commas in between
the values.
Datatypes in DBMS: DBMS have a wide range of datatypes. Some of the basic datatypes are mentioned in the below
given Table 1.
Table 1. Shows some of the frequently used datatype.
DATATYPE DESCRIPTION USAGE
CHAR String (0-255), can store characters of fixed length. CHAR(50)
VARCHAR String (0-255), can store characters up to a given length VARCHAR(50)
BLOB String, these can store large binary objects. BLOB(1000)
INT This stands for integer. INT
TINYINT This also stands for integer, but with a limit between -128 to TINYINT
127.
BIGINT This also stands for integer, but the range is much higher than BIGINT
TINYINT.
BIT This can store x-bit values. Where x ranges between 1 to 64 BIT(2)
FLOAT This is used to store decimal numbers. FLOAT
DOUBLE These are used to store decimal numbers with a range of 24 to DOUBLE
53 digits.
BOOLEAN These are used to store Boolean values. That is 0 and 1 BOOLEAN
DATE These are used to store date in the format of YYYY-MM-DD. DATE
YEAR These are used to store year in 4 digit format. Like: YYYY. YEAR
Furthermore, these are other two data types, these are: Signed and Unsigned datatypes. Signed datatypes are used to
differentiate between the negative integer and positive integer. Similarly, if a datatype are mentioned as UNSIGNED,
then it will only accept the value according to the described style. For example: if a datatype is marked as UNSIGNED
and the limit are mentioned as: 0 to 255, then it will only accept positive values. The code can be written as:
TINYINT UNSIGNED (0 TO 255);
Types of SQL commands: There are five types of SQL commands. These are as mentioned below:
• DDL (Data Definition Language): This allows the user to create, alter, rename, truncate and drop a database.
• DQL (Data Query Language): This allows the user to view the data using SELECT command.
• DML (Data Manipulation Language): These allows the user to manipulate the data. This manipulation can be
like entering a new data, deleting an old data etc.
• DCL (Data Control Language): This SQL commands provides permission to the users about their range of access.
For example: a database of students from a college, which includes several columns like: student_name,
registration_id, fee_payment, marks_obtained. This command will allow Accounts department to access the
history of fee payment, while it will allow the faculty members to access the section of marks obtained by the
student.
• TCL (Transaction Control Language): This command delas with start transactions, commit rollback etc.
Database related Queries: It must be noted that, two databases cannot have a similar name. so, if we try to create a
database and are not sure whether the name of the database are coming same or not, so, we use a code IF NOT
EXISTS with the CREATE DATABASE command. The code is shown below:
CREATE DATABASE IF NOT EXISTS college;
Now, as we have used the command IF NOT EXIST, it will only create another database if the name of the database
doesn’t exist. If there is another database named as the same, it will show a warning sign stating that the name of the
new database is same as that of an existing database. The same thing application for DROP DATABASE code. The
only difference is that we use IF EXISTS for dropping a database. This means we are instructing the machine to
delete the database mentioned only if any database like the same exists. The code for this operation are shown below:
DROP DATABASE IF EXISTS college;
Another command is there, that are generally used to view all the databases on the screen. This can be done by using
the code SHOW DATABASES. The code is shown below:
SHOW DATABASES;
Table related Queries: Queries related to table includes creating a table, inserting data, viewing table etc. these are
mentioned in the below sections. These are:
• Creating a Table: The codes that are required to create a table are shown below.
CREATE TABLE student (
registration_number INT PRIMARY KEY,
name VARCHAR(5O),
roll_number INT NOT NULL
);
• Inserting data in a Table:
After creating the table, now its time to insert data to that table. The commands to insert data in a table are shown
below:
INSERT INTO student
(regiatration_number, name, roll_number)
VALUES
(211560, “Subhomoy”, 156028),
(211561, “Sohom”, 156029),
(211562, “Saswata”, 156030),
(211563, “Sahil”, 156031);
• Viewing a Table: After completing the data entry, its important to check whether the data are inserted properly
or not. So, to check the data from a table, the following commands are used:
SELECT * FROM student;
Concept of Keys in DBMS: There are all total nine different keys in DBMS. But, here we will only learn about the
two most important keys. That are: Primary key and Foreign Key. These are mentioned below:
• Primary Key: This is a column in a table that helps in uniquely identifying each row. In a table, there can be only
one primary key. For example: Roll number or Registration number of a student. The primary key of a table can
not be null and must have to be unique.
• Foreign Key: A foreign key is a column that refers to the primary key in a different table. There can be more than
one or multiple foreign key. Foreign key can be duplicated or it can be null.
Constraints: SQL constraints are used to specify rules for a data in a table. In this part, some of the basic constraints
are explained. Example of SQL constraints are: NOT NULL, UNIQUE, PRIMARY KEY etc. etc.
• NOT NULL: This command indicates that the column can not be empty. There must be some value according to
the mentioned criteria. The code is written as follows:
id INT NOT NULL,
• UNIQUE: This command states that all the values of the column must be identical and unique. Using this
command would not allow a similar input for two different data. The code is written as:
id INT UNIQUE,
• PRIMARY KEY: This command makes a column unique and also specifies that this cannot be null. This helps
is uniquely identification of data in a table. The code is written as:
id INT PRIMARY KEY,
There is another way of setting primary key. The code is written as follows:
CREATE TABLE employee (
id INT,
name VARCHAR(50),
age INT NOT NULL,
PRIMARY KEY (id)
);
• FOREIGN KEY: This command prevent actions that destroys the links between the tables. Foreign key also acts
a primary link between two different tables. The code is written as:
CREATE TABLE employee (
emp_id INT,
FOREIGN KEY (emp_id) references emp(id)
);
• DEFAULT: This command sets a default value for a column. This comes to action when we forget to insert the
value for a particular data, if we insert a particular data then default value doesn’t work. The code is written as:
salary INT DEFAULT 25000
• CHECK: This command allows the user to set limit to the values that are to be inserted in the table. We can also
say that, we use this command to set conditions for a data in a table. The code is written as follows:
CREATE TABLE employee (
emp_id INT,
name VARCHAR(50),
city VARCHAR(20),
age INT NOT NULL,
CONSTRAINT age_check CHECK(age >= 27)
);
Before moving to the new section of commands, we will first create a new database. This database will be used further
for checking the use of commands. The codes for the new database are shown below:
CREATE DATADASE college;
USE college;
Cascading of Foreign Key: There are two types of cascading used to UPDATE and DELETE data from a table. Both
of these cascading techniques are mentioned below:
• ON DELETE CASCADE: When we use a foreign key using this caption, it also deletes the referencing rows in
the child table, when the references row are deleted from the parent table.
• ON UPDATE CASCADE: When we use a foreign key using ON UPDATE CASCADE command, the
referencing rows of the child table are also updated. The basic syntax to code this is shown below:
CREATE TABLE table_name (
col1 DATATYPE CONSTRAINTS,
col2 DATATYPE CONSTRAINTS,
col3 DATATYPE CONSTRAINTS,
FOREIGN KEY (col_name) REFERENCES table_name(col_name)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Now, if we want to apply the same thing on the above drawn table for department, teacher and student. The code
would be like:
CREATE TABLE student (
rollno INT PRIMARY KEY,
name VARCHAR(50),
dept_id INT NOT NULL,
marks INT NOT NULL,
grade VARCHAR(1),
FOREIGN KEY (dept_id) REFERENCES department(dept_id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Other Table Related Queries in SQL: Another important term in table query is ALTER. This command is used to
change the schema/design of the table. There are several operations that can be done using ALTER command. These
all are mentioned in below section:
• ADD column: This command is used along with the ALTER command. This is used to add a new column to an
existing table. A basic syntax for the same are shown below:
ALTER TABLE table_name
ADD COLUMN col_name DATATYPE CONSTRAINTS;
• DROP column: This command is used along with ALTER command to delete an existing table. A basic syntax
for the operation are shown below:
ALTER TABLE table_name
DROP COLUMN col_name;
• RENAME column: This command is used along with ALTER command to rename the name of an existing table.
The basic syntax for the operation are shown below:
ALTER TABLE table_name
RENAME TO new_table_name;
• CHANGE column: This command is used along with ALTER command to rename the name of an existing
column. The basic syntax to do so are shown below.
ALTER TABLE table_name
CHANGE COLUMN old_col_name new_col_name DATATYPE CONSTRAINTS;
• MODIFY column: This command is used along with the ALTER command to modify the datatype or constraints
of an existing column. The basic syntax are shown below:
ALTER TABLE table_name
MODIFY col_name new_datatype new_constraint;
• TRUNCATE: The TRUNCATE command is used to delete all the data from a table. The basic syntax for the
operation are shown below:
TRUNCATE TABLE table_name;
We have also learnt about DROP command. The main difference between DROP and TRUNCATE command is
that: DROP command deletes the complete table, whereas TRUNCATE command only deletes the data in the
table. If we want, we can again insert data into the same table, whereas if we use DROP command we will have
to create a table first after that we will be able to insert data.
JOINS in SQL: JOINS are used in SQL to combine rows from two or more tables, based on a related column between
them. For example: we have two different tables of employees. Table1 is named as “employee”, which consists of
“emp_id” and “emp_name”, whereas Table2 is named as “salary”, which includes “emp_id” and “salary_amount”.
Now if we want to see all the data that are common in both Table1 and Table2, then we will have to use JOINS. There
are mainly two types of JOINS. These are as described below:
• INNER JOINS: If we want to get the common data between two or more tables, then we use INNER joins. The
venn diagram for INNER JOIN is shown below. And the basic syntax to operate is shown below:
SELECT col_name
FROM table_name1
INNER JOIN table_name2
ON table_name1. col_name = table_name2. col_name;
• OUTER JOINS: OUTER JOINS are further divided into three different parts. These are as mentioned below:
1. LEFT JOIN: This join returns all records from the left table along with the matched records from the right
side table. The Venn diagram is shown below. The basic syntax to use LEFT JOIN are shown below:
SELECT col_name
FROM table_name1
LEFT JOIN table_name2
ON table_name1. col_name = table_name2. col_name;
2. RIGHT JOIN: This join all records from the right table along with the matched records from left table. The
Venn diagram are shown below. The basic syntax to use RIGHT JOIN are shown below:
SELECT col_name
FROM table_name1
RIGHT JOIN table_name2
ON table_name1. col_name = table_name2. col_name;
3. FULL JOIN: This join returns all records when there is a match in either left table or the right table. In
MySQL there are no commands like FULL JOIN. So, we use UNION command in between the results of
RIGHT JOIN and LEFT JOIN. The Venn diagram is shown below. The basic syntax to write the code in
MySQL is also shown below:
SELECT col_name
FROM table_name1
LEFT JOIN table_name2
ON table_name1. col_name = table_name2. col_name;
UNION
SELECT col_name
FROM table_name1
RIGHT JOIN table_name2
ON table_name1. col_name = table_name2. col_name;
Other JOINS in SQL: Apart from the major JOINS discussed above, there are two other different JOINS. These are:
Left Exclusive Join and Right Exclusive Join. The codes to operate them are shown below:
SELECT col_name
FROM table_name1
LEFT JOIN table_name2
ON table_name1. col_name = table_name2. col_name
WHERE table_name2. col_name IS NULL;
The above code shows the syntax for Left Exclusive Join and the code for Right Exclusive Join are shown below:
SELECT col_name
FROM table_name1
RIGHT JOIN table_name2
ON table_name1. col_name = table_name2. col_name
WHERE table_name1. col_name IS NULL;
SELF JOIN: It is a regular join, but the table are joined with itself. The basic syntax for SELF JOIN are given below:
SELECT col_name
FROM table_name1 AS table1
JOIN table_name1 AS table2
ON table1. col_name = table2. col_name;
Concept of UNION: It is used to combine the result set of two or more SELECT statements. And also, it gives unique
records. For example: if we have two different tables with some data/element common in between them, now if we
use the UNION command it will always give us the records of both the tables without the repetition of data. The basic
syntax to operate UNION command are as shown below:
SELECT col_name FROM table1
UNION
SELECT col_name FROM table2;
SQL Sub-Queries: A Sub-Query is a query within another SQL query. The Sub-Query is also known as Inner Query,
Nested Query. Usually, Sub-Queries are used within WHERE clause. The basic syntax for the operation of Sub-Query
are shown below:
SELECT col_name
FROM table_name
WHERE col_name operator (subquery);
To understand the condition and operation of subquery, we will take two examples. The examples are mentioned
below:
QUESTION SESSION:
Question_01. Get the name of all students who secure more than the class average. The table is given below:
roll_number name marks
101 Anil 78
102 Bhumika 93
103 Chetan 85
104 Dhruv 96
105 Farah 92
Answer_01: So, to get the accurate result, the SQL code would be:
SELECT name, marks
FROM student
WHERE marks > (SELECT AVG(marks) FROM student);
_____________________________________________________________________________