Unit 2 Rdbms
Unit 2 Rdbms
Introduction to SQL
● SQL stands for Structured Query Language
● SQL lets you access and manipulate databases
● Structure query language is not case sensitive. Generally, keywords of SQL are
written in uppercase.
● 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 RDBMS.
● 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.
CHAR(size) It is used to store character data within the predefined length. It can
be stored up to 2000 bytes.
NCHAR(size It is used to store national character data within the predefined length.
) It can be stored up to 2000 bytes. Ex.: $, #, and @
VARCHAR2( It is used to store variable string data within the predefined length. It
size) can be stored up to 4000 byte.
NVARCHAR It is used to store Unicode string data within the predefined length.
2(size) We have to must specify the size of NVARCHAR2 data type. It can
be stored up to 4000 bytes. Ex.: cm, m, km, inch, etc.
NUMBER(p, It contains precision p and scale s. The precision p can range from 1
s) to 38, and the scale s can range from -84 to 127.
FLOAT(p) It is a subtype of the NUMBER data type. The precision p can range
from 1 to 126.
TIMEST It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss
AMP format.
SQL Components
● DDL:-Data Definition Language
● DML:-Data Manipulation Language
● DCL:-Data Control Language
● TCL:-Transaction Control Language
Create Command:
Syntax:
(col1 datatype(size),
Col2 datatype(size));
Example:-
emp_name varchar2(10),
Job varchar2(30),
Salary number(12,2),
Dept_no number(2));
Alter Statement:
Syntax:
Example:-
DROP Statements:-
● DROP TABLE statement removes tables and their data from the database
● A table cannot be dropped if it contains foreign key values needed by other
tables
Syntax:
Example:
RENAME Statement:-
Syntax:
Example:
Truncate Command:
● Remove all records from a table, including all spaces allocated for the records
are removed.
Syntax:
Example:
● Select
● Insert
● Update
● Delete
Select Command:
Syntax:
If we want to retrieve the data from all the columns of the table, we have to use the
following SELECT command:
Example:
Example 1: This example shows all the values of every column from the table.
Example 2: This example shows all the values of a specific column from the table.
Example 3: This example describes how to use the WHERE clause with the SELECT
DML command.
Insert Command:
INSERT is another most important data manipulation command in Structured Query
Language, which allows users to insert data in database tables.
Syntax:
Example:
Update Command:
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.
Syntax:
Here, 'UPDATE', 'SET', and 'WHERE' are the SQL keywords, and 'Table_name' is the
name of the table whose values you want to update.
Examples
Example 1: This example describes how to update the value of a single field.
Example 2: This example describes how to update the value of multiple fields of the
database table.
DELETE Command:
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.
Syntax
Examples
Example 1: This example describes how to delete a single record from the table.
Example 2: This example describes how to delete the multiple records or rows from the
database table.
➔ DELETE FROM Student WHERE Stu_Marks > 70 ;
DCL is an abbreviation for Data Control Language in SQL. It is used to provide different
users access to the stored data. It enables the data administrator to grant or revoke the
required access to act as the database. When DCL commands are implemented in the
database, there is no feature to perform a rollback. The administrator must implement
the other DCL command to reverse the action.
● GRANT
● REVOKE
GRANT Command
It helps to provide any kind of access to any user.
GRANT, as the name itself suggests, provides. This command allows the administrator
to provide particular privileges or permissions over a database object, such as a table,
view, or procedure. It can provide user access to perform certain database or
component operations.
In simple language, the GRANT command allows the user to implement other SQL
commands on the database or its objects. The primary function of the GRANT
command in SQL is to provide administrators the ability to ensure the security and
integrity of the data is maintained in the database.
Consider a scenario where you are the database administrator, and a student table is in
the database. Suppose you want a specific user Aman to only SELECT (read)/ retrieve
the data from the student table. Then you can use GRANT in the below GRANT
statement.
Create User:
Syntax:
Example:
This command will allow Aman to implement the SELECT queries on the student table.
This will enable the user to read or retrieve information from the student table.
Note: Implementing the above statement will also limit Aman's operations. Aman won't be
able to modify the data stored in the table. It will prevent the user from user to insert, to
update, or deleting the data in the student table in the database.
REVOKE Command
As the name suggests, revoke is to take away. The REVOKE command enables the
database administrator to remove the previously provided privileges or permissions
from a user over a database or database object, such as a table, view, or procedure.
The REVOKE commands prevent the user from accessing or performing a specific
operation on an element in the database.
In simple language, the REVOKE command terminates the ability of the user to perform
the mentioned SQL command in the REVOKE query on the database or its component.
The primary reason for implementing the REVOKE query in the database is to ensure
the data's security and integrity.
Let us use an example to better understand how to implement the REVOKE command
in SQL.
Consider a scenario where the user is the database administrator. In the above
implementation of the GRANT command, the user Aman was provided permission to
implement a SELECT query on the student table that allowed Aman to read or retrieve
the data from the table. Due to certain circumstances, the administrator wants to revoke
the above mentioned permission. To do so, the administrator can implement the below
REVOKE statement:
This will stop the user Aman from implementing the SELECT query on the student table.
The user may be able to implement other queries in the database.
There are certain commands present in SQL known as TCL commands that help the
user manage the transactions that take place in a database.
COMMIT. ROLLBACK and SAVEPOINT are the most commonly used TCL commands
in SQL.
Now let us take a deeper dive into the TCL commands of SQL with the help of
examples. All the queries in the examples will be written using the MySQL database.
COMMIT
Syntax:
COMMIT;
Example:
SQL> commit;
ROLLBACK:-
Syntax:
Rollback;
Example:
In example , do not insert the record in the Salesman table because use rollback.
SAVEPOINT :-
Syntax:
Example:
In the savepoint B statement do not insert 1004, 1005 data because use rollback.
SQL constructs
Group by Clause:-
Group by clause from a group on the basis of similar types data and produce a separate
table.
Note: The group by clause performs its operation in the buffer not in the database.
In SQL, The Group By statement is used for organizing similar data into groups. The
data is further organized with the help of equivalent function. It means, if different rows
in a precise column have the same values, it will arrange those rows in a group.
Group By single column: Group By single column is used to place all the rows with the
same value. These values are of that specified column in one group. It signifies that all
rows will put an equal amount through a single column, which is of one appropriate
column in one group.
○ The SELECT statement is used with the GROUP BY clause in the SQL query.
Emp:
1 Sale 10000
2 HR 15000
3 Sale 20000
4 Sale 10000
5 HR 23000
6 Product 25000
Example:
SQL> SELECT DNAME FROM Emp GROUP BY DNAME;
Output:
DNAME
----------
Sale
HR
Product
Example:
SQL> SELECT DNAME,COUNT(*) FROM Emp GROUP BY DNAME;
Output:
DNAME COUNT(*)
---------- --------
Sale 4
HR 2
Product 1
Having Clause:-
Syntax:
Example:
SQL> SELECT DNAME,COUNT(*) FROM Emp GROUP BY DNAME HAVING
COUNT(*) >=2;
Output:
DNAME COUNT(*)
---------- --------
Sale 3
HR 2
Order by Clause:-
● We use order by clause to arrange the records of one or more columns either
ascending or descending order.
● Whenever we want to sort the records based on the columns stored in the tables
of the SQL database, then we consider using the ORDER BY clause in SQL.
● The ORDER BY clause in SQL will help us to sort the records based on the
specific column of a table. This means that all the values stored in the column on
which we are applying ORDER BY clause will be sorted, and the corresponding
column values will be displayed in the sequence in which we have obtained the
values in the earlier step.
ascending order whenever the ASC keyword is used with ORDER by clause.
DESC keyword will sort the records in descending order.
Syntax:
SELECT ColumnName1,...,ColumnNameN FROM TableName ORDER BY
ColumnName ASC/DESC;
Example:
SQL> SELECT *FROM Emp ORDER BY EID ASC;
SQL Functions
String Functions
SQL String functions are the predefined functions that allow the database users for
string manipulation. These functions only accept, process, and give results of the string
data type.
In Oracle SQL, the DUAL table is a special one-row, one-column table provided by
Oracle.The DUAL table has one column called DUMMY of type VARCHAR2(1) with a
value of 'X'.
Following are the most important string functions in Structured Query Language:
1) Upper(string)
2) Lower(string)
Output: india
3) Initcap(string)
4) Ascii(character)
Output: 65
5) Char(number)
Output: A
6) Length(string)
Output: 5
7) Ltrim(string)
Output: Morning
8) Rtrim(string)
Output: Good
Output: OD MORNING
Output: ODM
10) Instr(string)
Output: 6
Output: 2
Output: KNIFE
Output: GOODMORNING
Output: GOODMORNING
Conversion Functions
1)To_char(Date,Format)
Output: 29-07-24
Output: 29-JULY-2024
2)To_date(string,’Format’)
Output: 29-JUL-24
Output: 29-JUL-24
Numeric Functions
1) Round(number,rounding place)
Output: 50
Output: 51
Output: 50.61
Output: 1
3) Sqrt(number)
Output: 3
4) Abs(number)
Output: 52
Output: 5.5
5) Power(number,paised number)
Output: 25
6) Trunc(number)
Output: 52
7) Ceil(number)
Output: 141
Output: 140
8) Floor(number)
Output: 140
Aggregate Functions
1)Sum(column name)
2) Avg(column name)
3) Min(column name)
Output: 4500
4) Max(column name)
Output: 8000
5) Count(*)
6) Count(column)
– Count() function count total number of record in table without null value.
Set Operators
SET operators are special type of operators which are used to combine the result of two
queries.
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
There are certain rules which must be followed to perform operations using SET
operators in SQL. Rules are as follows:
Let us see each of the SET operators in more detail with the help of examples.
Table 1: t_employees
Table 2: t2_employees
1. UNION:
● Duplicate rows will be eliminated from the results obtained after performing the
UNION operation.
Example:
Write a query to perform union between the table t_employees and the table
t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query
will fetch the records from the t_employees table and perform a UNION operation with
the records fetched by the second SELECT query from the t2_employees table.
2. UNION ALL
● This operator combines all the records from both the queries.
● Duplicate rows will be not be eliminated from the results obtained after
performing the UNION ALL operation.
Example:
Write a query to perform union all operation between the table t_employees and the
table t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query
will fetch the records from the t_employees table and perform UNION ALL operation
with the records fetched by the second SELECT query from the t2_employees table.
3. INTERSECT:
● It is used to combine two SELECT statements, but it only returns the records
which are common from both SELECT statements.
Example:
Write a query to perform intersect operation between the table t_employees and the
table t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query
will fetch the records from the t_employees table and perform INTERSECT operation
with the records fetched by the second SELECT query from the t2_employees table.
4. MINUS
● It displays the rows which are present in the first query but absent in the second
query with no duplicates.
Example:
Write a query to perform a minus operation between the table t_employees and the
table t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query
will fetch the records from the t_employees table and perform MINUS operation with the
records fetched by the second SELECT query from the t2_employees table.
● You can place the Subquery in a number of SQL clauses: WHERE clause,
HAVING clause, FROM clause. Subqueries can be used with SELECT,
UPDATE, INSERT, DELETE statements along with expression operator. It
could be equality operator or comparison operator such as =, >, =, <= and
Like operator.
● A subquery is a query within another query. The outer query is called as main
query and inner query is called as subquery.
● The subquery generally executes first when the subquery doesn’t have any
correlation with the main query, when there is a correlation the parser takes
the decision on the fly on which query to execute on precedence and uses
the output of the subquery accordingly.
● Subquery must be enclosed in parentheses.
● Subqueries are on the right side of the comparison operator.
● Use single-row operators with single row Subqueries. Use multiple-row
operators with multiple-row Subqueries.
Syntax: There is not any general syntax for Subqueries. However, Subqueries are seen
to be used most frequently with SELECT statement as shown below:
SELECT column_name
FROM table_name
Sample Table:
DATABASE
STUDENT
Ravi 104 A
Sumathi 105 B
Raj 102 A
Sample Queries:
FROM DATABASE
FROM STUDENT
WHERE SECTION='A');
Output:
Table1: Student1
Table2: Student2
Output:
FROM Student1
Examples
Correlated subqueries in the WHERE clause
Here is an example for a typical correlated subquery. In this example, the objective is to
find all employees whose salary is above average for their department.
SELECT AVG(salary)
FROM employees
SELECT AVG(salary)
FROM employees
In the above nested query the inner query has to be re-executed for each employee. (A
sufficiently smart implementation may cache the inner query's result on a department-
by-department basis, but even in the best case the inner query must be executed once
per department.)
Correlated subqueries may appear elsewhere besides the WHERE clause; for example,
this query uses a correlated subquery in the SELECT clause to print the entire list of
employees alongside the average salary for each employee's department. Again,
because the subquery is correlated with a column of the outer query, it must be re-
executed for each row of the result.
Correlated subqueries may appear elsewhere besides the WHERE clause; for example,
this query uses a correlated subquery in the SELECT clause to print the entire list of
employees alongside the average salary for each employee's department. Again,
because the subquery is correlated with a column of the outer query, it must be re-
executed for each row of the result.
SQL Joins
Sometimes it is necessary to work with multiple tables as though they were a single
entity. Then a single SQL sentence can manipulate data from all the tables. Joins are
used to achieve this. Tables are joined on columns that have the same data type and
data width in the tables.
Tables in a database can be related to each other with keys. A primary key is a column
with a unique value for each row. The purpose is to bind data together, across tables,
without repeating all of the data in every table.
Types of JOIN:
● Inner Join
● Outer Join (Left, Right, Full)
Syntax
SELECT column_name(s)
FROM table1
ON table1.column_name = table2.column_name;
➔ Find the Emp name who worked in a department having location same as their
address.
1 Ram Delhi
2 Varun Chd
3 Ravi Chd
4 Amrit Delhi
D1 Delhi 1
D2 Pune 2
D3 Patna 4
SQL> Select E_Name from Emp, Dept where Emp.E_No = Dept.E_No and
Emp.Address = Dept.Location;
Left Join
It gives the matching rows and the rows which are in left table but not in right table.
Syntax:
E1 Varun D1
E2 Amrit D2
E3 Ravi D1
E4 Nitin -
D1 IT Delhi
D2 HR Hyd
D3 Finance Pune
SQL> Select Emp_No, E_Name, D_Name, Location from Emp LEFT OUTER JOIN
Output:
E1 Varun IT Delhi
E2 Amrit HR Hyd
E3 Ravi IT Delhi
E4 Nitin - -
Right Join
It gives the matching rows and the rows which are in the Right table but not in the Left
table.
Syntax:
E1 Varun D1
E2 Amrit D2
E3 Ravi D3
D1 IT Delhi
D2 HR Hyd
D3 Finance Pune
D4 Testing Noida
SQL> Select Emp_No, E_Name, D_Name, Location from Emp RIGHT OUTER JOIN
Output:
E1 Varun IT Delhi
E2 Amrit HR Hyd
- - Testing Noida
Full Outer Join contains the results of both the Left and Right outer joins. It is also
known as cross-join. It will provide a mixture of two tables.
Full Outer Join returns all the rows from both tables, including matching and non-
matching rows. If a row in one table does not have a matching row in the other table,
the result set will include NULL values for the columns in the table that do not have a
match.
Syntax:
SELECT * FROM T1
CROSS-JOIN T2;
E1 Varun D1
E2 Amrit D2
E3 Ravi D3
D1 IT Delhi
D2 HR Hyd
D3 Finance Pune
D4 Testing Noida
Output:
E_Name D_Name
Varun IT
Amrit HR
Ravi Finance
- Testing
Integrity constraints are the set of predefined rules that are used to maintain the quality
of information. Integrity constraints ensure that the data insertion, data updating, data
deleting and other processes have to be performed in such a way that the data integrity
is not affected. They act as guidelines ensuring that data in the database remain
accurate and consistent. So, integrity constraints are used to protect databases. The
various types of integrity constraints are
1. Domain constraints
● Domain constraints can be defined as the definition of a valid set of values for an
attribute.
● The data type of domain includes string, character, integer, time, date, currency,
etc. The value of the attribute must be available in the corresponding domain.
Example:
● The entity integrity constraint states that primary key value can't be null.
● This is because the primary key value is used to identify individual rows in
relation and if the primary key has a null value, then we can't identify those rows.
● A table can contain a null value other than the primary key field.
Example:
Example:
4. Key constraints
● Keys are the entity set that is used to identify an entity within its entity set
uniquely.
● An entity set can have multiple keys, but out of which one key will be the primary
key. A primary key can contain a unique and null value in the relational table.
Example: