DBMS Unit 3 - Part 1 Final
DBMS Unit 3 - Part 1 Final
SQL (Structured Query Language) is used to perform operations on the records stored in the
database, such as updating records, inserting records, deleting records, creating and modifying
database tables, views, etc.
Suppose you want to perform the queries of SQL language on the stored data in the database.
You are required to install any database management system in your systems, for example,
Oracle, MySQL, MongoDB, PostgreSQL, SQL Server, DB2, etc.
What is SQL?
This database language is mainly designed for maintaining the data in relational database
management systems. It is a special tool used by data professionals for handling structured data
(data which is stored in the form of tables). It is also designed for stream processing in RDSMS.
You can easily create and manipulate the database, access and modify the table rows and
columns, etc. This query language became the standard of ANSI in the year of 1986 and ISO in
the year of 1987.
If you want to get a job in the field of data science, then it is the most important query language
to learn. Big enterprises like Facebook, Instagram, and LinkedIn, use SQL for storing the data in
the back-end.
Why SQL?
Nowadays, SQL is widely used in data science and analytics. Following are the reasons which
explain why it is widely used:
○ The basic use of SQL for data professionals and SQL users is to insert, update, and delete
the data from the relational database.
○ SQL allows the data professionals and users to retrieve the data from the relational
database management systems.
○ It allows SQL users to create, drop, and manipulate the database and its tables.
UNIT - 3 SQL
○ It also helps in creating the view, stored procedure, and functions in the relational
database.
○ It allows you to define the data and modify that stored data in the relational database.
○ It also allows SQL users to set the permissions or constraints on table columns, views,
and stored procedures.
The SQL commands help in creating and managing the database. The most common SQL
commands which are highly used are mentioned below:
1. CREATE command
2. UPDATE command
3. DELETE command
4. SELECT command
5. DROP command
6. INSERT command
CREATE Command
This command helps in creating the new database, new table, table view, and other objects of the
database.
column1 datatype,
column2 datatype,
This command helps in updating or changing the stored data in the database.
WHERE condition;
ALTER TABLE
ALTER TABLE changes the structure of a table. Here is how you would add a column to a
database:
DELETE Command
This command helps in removing or erasing the saved records from the database tables. It erases
single or multiple tuples from the tables of the database.
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
DELETE FROM table_name;
This command helps in accessing the single or multiple rows from one or multiple tables of the
database. We can also use this command with the WHERE clause.
FROM table_name;
DROP Command
This command helps in deleting the entire table, table view, and other objects from the database.
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table
itself.
INSERT Command
This command helps in inserting the data or records into the database tables. We can easily insert
the records in single as well as multiple rows of the table.
—------------------------------------------------------------------------------------------------------------------
The DDL Commands in Structured Query Language are used to create and modify the schema of
the database and its objects. The syntax of DDL commands is predefined for describing the data.
The commands of Data Definition Language deal with how the data should exist in the database.
1. CREATE Command
2. DROP Command
3. ALTER Command
4. TRUNCATE Command
5. RENAME Command
CREATE Command
CREATE is a DDL command used to create databases, tables, triggers and other database
objects.
...
DROP Command
DROP is a DDL command used to delete/remove the database objects from the SQL database.
We can easily remove the entire table, view, or index from the database using this DDL
command.
ALTER Command
ALTER is a DDL command which changes or modifies the existing structure of the database,
and it also changes the schema of database objects.
We can also add and drop constraints of the table using the ALTER command.
TRUNCATE Command
TRUNCATE is another DDL command which deletes or removes all the records from the table.
This command also removes the space allocated for storing the table records.
RENAME Command
RENAME is a DDL command which is used to change the name of the database table.
—---------------------------------------------------------------------------------------------------------
DML Commands in SQL
The DML commands in Structured Query Language change the data present in the SQL
database. We can easily access, store, modify, update and delete the existing records from the
database using DML commands.
1. SELECT Command
2. INSERT Command
UNIT - 3 SQL
3. UPDATE Command
4. DELETE Command
SELECT is the most important data manipulation command in Structured Query Language. The
SELECT command shows the records of the specified table. It also shows the particular record
of a particular column by using the WHERE clause.
If we want to retrieve the data from all the columns of the table, we have to use the
following SELECT command:
INSERT is another most important data manipulation command in Structured Query Language,
which allows users to insert data in database tables.
UPDATE is another most important data manipulation command in Structured Query Language,
which allows users to update or modify the existing data in database tables.
DELETE is a DML command which allows SQL users to remove single or multiple existing
records from the database tables.
This command of Data Manipulation Language does not delete the stored data permanently from
the database. We use the WHERE clause with the DELETE command to select specific rows
from the table.
—------------------------------------------------------------------------------------------------------------------
DCL commands are used to grant and take back authority from any database user.
○ Grant
○ Revoke
Example
Example
—------------------------------------------------------------------------------------------
UNIT - 3 SQL
SQL CREATE TABLE
If you want to create a table, you should name the table and define its column and each column's
data type.
...
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.
The basic syntax for creating a table with the other table is:
FROM Employee;
UNIT - 3 SQL
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.
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.
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:
column_Name2 column-definition,
.....
column_NameN column-definition);
ALTER TABLE MODIFY Column statement in SQL
The MODIFY keyword is used for changing the column definition of the existing table.
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.
UNIT - 3 SQL
ALTER TABLE table_name
column_Name2 column-definition,
.....
column_NameN column-definition);
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.
The RENAME keyword is used for changing the name of columns or fields of the existing table.
—------------------------------------------------------------------------------------------------------------------
DEFINING CONSTRAINTS:
There are certain keys in DBMS that are used for different purposes, from which the most
commonly known is the Primary Key.
Here, in this section, we will look at the Primary key - What it is, what is the use of a primary
key, and we will also implement some examples to understand that how a primary key works.
A Primary Key is the minimal set of attributes of a table that has the task to uniquely identify the
rows, or we can say the tuples of the given particular table.
UNIT - 3 SQL
A primary key of a relation is one of the possible candidate keys which the database designer
thinks it's primary. It may be selected for convenience, performance and many other reasons. The
choice of the possible primary key from the candidate keys depend upon the following
conditions.
The primary key constraint can be defined at the column level or table level.
At column level:
It is also possible to delete the set primary key from an attribute using ALTER and DROP
commands.
In order to set the primary key after creating a table, use the ALTER command and add the
primary key constraint to do so. The syntax is shown below:
We have taken the Name attribute just for understanding the syntax.
To create a foreign key on the "S_Id" column when the "Orders" table is created:
UNIT - 3 SQL
CREATE TABLE orders
S_Id int,
If the Order table is already created and you want to create a FOREIGN KEY constraint on the
"S_Id" column, you should write the following syntax:
FOREIGN KEY(S_Id)
If you want to drop a FOREIGN KEY constraint, use the following syntax:
A unique key is a set of one or more than one fields/columns of a table that uniquely identify a
record in a database table.
You can say that it is little like primary key but it can accept only one null value and it cannot
have duplicate values.
The unique key and primary key both provide a guarantee for uniqueness for a column or a set of
columns.
There is an automatically defined unique key constraint within a primary key constraint.
There may be many unique key constraints for one table, but only one PRIMARY KEY
constraint for one table.
If you want to create a UNIQUE constraint on the "S_Id" column when the "students" table is
created, use the following SQL syntax:
—---------------------------------------------------------
—----------------------------------------------------------
—--------------------------------------------------------------
If you want to create a unique constraint on "S_Id" column when the table is already created, you
should use the following SQL syntax:
If you want to drop a UNIQUE constraint, use the following SQL syntax:
—--------------------------------------------------------
UNIT - 3 SQL
ALTER TABLE students
If you don’t want to have a null column or a null value you need to define constraints like NOT
NULL. NOT NULL constraints make sure that a column does not hold null values, or in other
words, NOT NULL constraints make sure that you cannot insert a new record or update a record
without entering a value to the specified column(i.e., NOT NULL column).
Syntax:
—--------------------------------------------------------------------------------
Check Constraint:
Let us see a few practical examples to understand this concept more clearly. We will use the
MariaDB database for writing all the queries.
UNIT - 3 SQL
Check constraint on column level:
To apply a check constraint on a column level, we must specify the check constraint just after the
column name.
Syntax:
We will write a query to create a table and specify a column-level check constraint on more than
one column.
In the above query, we have specified the CHECK constraint on the Percentage and
Favourite_Subject column. According to this constraint, the Percentage column will allow only
those records to be inserted where the percentage secured by students is above 90, and the
favourite subject of the student is either Science, Maths or English.
To apply a check constraint on a table level, we must specify the check constraint before ending
the table creation.
Syntax:
UNIT - 3 SQL
CREATE TABLE TableName(ColumnName1 Datatype(size), ColumnName2 Datatype(size),
ColumnName3 Datatype(size),…, ColumnNameN Datatype(size), Constraint ConstraintName
CHECK(ColumnName CONDITION Value));
We will write a query to create a table and specify a table-level check constraint on more than
one column.
A situation may arise when we need to apply a check constraint on a column after the table
creation. In such cases, we have to use the ALTER command to apply the check constraint on an
already created table.
Syntax:
Suppose we created an employ table without any constraints, and later we decided to add a
constraint on one of the columns. Then we will execute the following query:
Suppose we have a check constraint created on the table's column. Later, we decided to remove
that constraint from the column. Then, in such a situation, we will use the ALTER command to
remove the check constraint.
Syntax:
—------------------------------------------------------------------------------------------------------------------
SQL IN Operator
Write a query to display all the records from the t_students table where the hometown of the
students is one of the following places: Faridabad, Panipat, or Jaipur.
Write a query to display all the records from the t_students table where the favourite subject of
the students is one of the following subjects: History, Biology, Physics or Chemistry.
Query: mysql> SELECT *FROM t_students WHERE Percentage IN (78, 88, 89, 90, 92);
Write a query to display all the records from the employee table where the date of birth of an
employee is one of the following dates: 1999-01-10, 1989-01-09, 1993-03-05, or 1993-05-03.
Write a query to display all the records from the employee table where the job location of an
employee is among one of the following places: Nashik, Surat, Noida, Delhi, or Pune.
Write a query to display all the records from the employee table where the salary of an employee
is among one of the following values: 60000, 53000, 30000, or 45000.
Query: mysql> SELECT *FROM employee WHERE Salary IN (60000, 53000, 30000, 45000);
—--------------------------------------------------------------------------------------------------
In this article let us explore a new topic in SQL called aggregate functions. First let us
understand what is aggregate function and how does it actually work.
Aggregate functions in SQL are unique functions that work on a group of rows in a table and
produce a single value as a result. These operations are used to calculate a set of numbers and
produce summary statistics like sum, count, average, maximum, and minimum. SQL queries
frequently employ aggregate procedures to condense data from one or more tables.
UNIT - 3 SQL
After grouping and aggregating, aggregate functions can also be used with the HAVING or
WHERE clause to further filter the data. A condition involving an aggregate function can be
used to filter the results of a query using the HAVING or WHERE clause.
Below are a few frequently used aggregate functions in SQL. Let us understand each of these
functions with the help of various examples.
1. Count()
2. Sum()
3. Avg()
4. Min()
5. Max()
1. COUNT():
This function returns the number of records(rows) in a table. The Syntax of the count() function is
mentioned below.
2. SUM ():
This function returns the sum of all values of a column in a table. Here is the syntax for the sum()
function.
3. AVG ()
This function will return the average of all values present in a column. The syntax of the AVG()
function is given below.
This function produces the lowest value in a column for a group of rows that satisfy a given
criterion. The Syntax of the MIN() function is as follows
5. MAX()
The MAX function in SQL is used to return the highest value in a column for a group of rows that
satisfy a given condition in a table. The MAX syntax is as follows:
—------------------------------------------------------------------------------------------------------------------
The following is the list of built-in String functions, DateTime functions, Numeric functions and
conversion functions.
String Functions
ASCII Returns the ASCII code value for the leftmost character of a
character expression.
CONCAT Concatenates two or more string values in an end to end manner and
returns a single string.
NCHAR Returns the Unicode character with the specified integer code, as
defined by the Unicode standard.
PATINDEX Returns the starting position of the first occurrence of the pattern in a
given string.
RIGHT Returns the right part of a string with the specified number of
characters.
UNIT - 3 SQL
STR Returns character data converted from numeric data. The character
data is right justified, with a specified length and decimal precision.
DateTime Functions
CURRENT_ Returns the current system date and time of the computer on which the
SQL server instance is installed. Time zone is not included.
TIMESTAMP
DAY Returns the Day as an integer representing the Day part of a specified
date.
GETDATE Returns a datetime value containing the date and time of the computer
on which the SQL Server instance is installed. It does not include the
time zone.
YEAR Returns the Year as an integer representing the Year part of a specified
date.
UNIT - 3 SQL
ISDATE Determines whether the input is a valid date, time or datetime value.
Numeric Functions
CEILING Returns the nearest integer value which is larger than or equal to the specified
decimal value.
FLOOR Returns the largest integer value that is less than or equal to a number. The
return value is of the same data type as the input parameter.
RAND Returns a random floating point value using an optional seed value.
UNIT - 3 SQL
SUM Returns the sum of all the values or only the distinct values, in the expression.
NULL values are ignored.
A set operator in SQL is a keyword that lets you combine the results of two queries into a single
query.
Sometimes when working with SQL, you’ll have a need to query data from two more tables. But
instead of joining these two tables, you’ll need to list the results from both tables in a single
result, or in different rows. That’s what set operators do.
There are a few different set operators that can be used, depending on your needs, and which
database vendor you’re using.
● UNION
● UNION ALL
● MINUS
● INTERSECT
● EXCEPT
UNIT - 3 SQL
Using Set Operators
SELECT your_select_query
set_operator
SELECT another_select_query;
It uses two (or more) SELECT queries, with a set operator in the middle.
When selecting your columns, the number of columns needs to match between queries, and the
data type of each column needs to be compatible.
So, if you select three columns in the first query, you need to select three columns in the second
query. The data types also need to be compatible, so if you select a number and two character
types in the first query, you need to do the same in the second query.
Also, if you want to order your results, the ORDER BY must go at the end of the last query. You
can’t add ORDER BY inside each SELECT query before the set operator.
The UNION keyword or set operator will allow you to combine the results of two queries. It
removes any duplicate results and shows you the combination of both.
If we wanted to select from both the employee and customer tables, using UNION, our query
would look like this:
The UNION ALL set operator also combines the results from two queries.
Let’s see an example. If we wanted to select from both the employee and customer tables, using
UNION ALL, our query would look like this:
FROM customer
UNION ALL
FROM employee;
Another set operator we can use is the MINUS keyword or the EXCEPT keyword.
The MINUS set operator will return results that are found in the first query specified that don’t
exist in the second query.
The EXCEPT keyword is similar to MINUS, but is available in SQL Server and other databases.
Using our example data, we could use the MINUS set operator to find all names in the customer
table that don’t exist in the employee table.
FROM customer
UNIT - 3 SQL
MINUS
FROM employee;
The INTERSECT keyword allows you to find results that exist in both queries. Two SELECT
statements are needed, and any results that are found in both of them are returned if
INTERSECT is used.
Using our example data, we could use the INTERSECT set operator to find all names in the
customer table that don’t exist in the employee table.
FROM customer
INTERSECT
FROM employee;