DBMS - Unit Iv
DBMS - Unit Iv
DBMS - Unit Iv
Introduction:
SQL (Structured Query Language) is a language that provides an interface to relational database
systems.
SQL was developed by IBM in 1970s for use in System R. SQL is an ANSI (American National
Standards Institute) standard
Features of SQL:
SQL can be easily used by a range of users with little or no knowledge of programming.
It is a non-procedural language
It reduces the amount of time required for modifying SQL statements.
It is an English like language and easy to understand.
Table:
The data in an RDBMS is stored in database objects which are called as tables. This table is basically a
collection of related data entries and it consists of numerous columns and rows. Remember a table is the
most common and simplest form of data storage in a relational database. The following program is an
example of a CUSTOMERS table
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3| kaushik|23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|
+ + + + + +
Field or Column:
Every table is broken up into smaller entities called fields(also called as attributes).A field is a column in
a table that is designed to maintain specific information about every record in the table. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.
Record or a Row:
A record is also called as a row of data is each individual entry that exists in a table. For example, there
are 7 records in the above CUSTOMERS table.
SQL Commands
• SQL commands are instructions used to communicate with the database to perform specific task that
work with data.
• SQL commands can be used not only for searching the database but also to perform various other
functions like, for example, you can create tables, add data to tables, or modify data, drop the table,
set permissions for users.
• SQL commands are grouped into four major categories depending on their functionality:
1. Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and
dropping the structure of database tables. The commands are CREATE, ALTER, DROP, RENAME, and
TRUNCATE.
2. Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving,
modifying, and deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.
3. Transaction Control Language (TCL) - These SQL commands are used for managing changes
affecting the data. These commands are COMMIT, and ROLLBACK.
4. Data Control Language (DCL) - These SQL commands are used for providing security to database
objects. These commands are GRANT and REVOKE.
Data Definition Language (DDL)- These SQL commands are used for creating, modifying and dropping
the structure of database tables. The commands are:
CREATE, ALTER, DROP, RENAME, and TRUNCATE.
1. Create Statement: This command is used for creating the structure of a table; Using this command
we specify the details like name of the column, datatype, size and constraints
Ans:- Create table EMPLOYEES(Employee_Id number(4) primary key , First_Name varchar2(20) not null,
Last_Name varchar2(20) not null, Email varchar2(40) unique, Phone_Number number(10), Hire_Date
date not null, Job varchar2(20) not null, Salary number(10,2) not null , Commission_Pct number(3),
Manager_Id number(4) references EMPLOYEES(Employee_Id), Department_Id number(2));
2. Alter statement: This command is used for changing the structure of a table.
• Using this command we can add a new constraint or a new column to table.
• We can also modify the datatype and size of the column.
• We can increase the size of a column but not decrease.
3. Drop statement: This command is used for deleting the table structure permanently from the
database. When this command is used the data present in the table and the structure of table is
deleted permanently from the database.
Syntax: drop table table-name;
Eg:- delete table student from the database SQL> drop
table student;
4. Rename Statement: This command is used for changing the name of a table.
5. Truncate:
• This command is used for permanently deleting complete data present in the table.
• The structure of the table is retained.
Syntax: SQL>TRUNCATE TABLE table_name; Eg:-
Delete the data present in Student table. Ans:-
SQL>truncate table student;
• These SQL commands are used for storing, retrieving, modifying, and deleting data.
• These commands are INSERT, UPDATE, DELETE and SELECT.
• After using DML commands we need to use commit statement to save the changes
permanently in the table.
1. Insert:
• The SQL INSERT Statement is used to add a new row of data into a table in the database.
Example: Inserting data for specified columns into customer table INSERT INTO
CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1,'Ramesh',32,'Ahmedabad',2000.00);
We need not specify the column(s) name in the SQL query if we are adding values for all the columns of
the table.But make sure the order of the values is in the same order as the columns in the table.
2. Update:
• The update query is used to change/modify/insert the data of a table for existing records.
• The UPDATE statement allows you to update a single record or multiple records in a table.
Syntax: UPDATE table SET column = newvalue WHERE condition;
Example: update all supplier names in the suppliers table from IBM to HP.
SQL>UPDATE suppliers SET name = 'HP' WHERE name = 'IBM';
3. Delete:
• The SQL DELETE Query is used to delete the existing records from a table.
• You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would
be deleted.
Syntax: DELETE FROM table_name WHERE [condition];
Example1: delete all the records of employee table Ans:
Delete from employee;
4. Select Statement
• SQL SELECT statement is used to fetch the data from a database table which returns data in the form
of result table.
• A query may retrieve information from specified columns or from all of the columns in the table.
Syntax of SQL SELECT Statement - global selection)
SELECT column_list FROM table_name
[WHERE Clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];
• table-name is the name of the table from which the information is retrieved.
• [WHERE Clause] is used for filtering the data according to the given criteria
• [GROUP BY clause] is used for grouping the data according to the given column
• [HAVING clause] is used to apply filter on the rows obtained after group by clause.
• [ORDER BY clause] is used to sort the data in ascending or descending order according to the given
column.
3. Select Specified columns and specified rows: Q: display employee id and name whose dept is
“sales”
Ans: SQL> select empid,ename from employee where dept = „sales‟;
Example1: Display the names of employees who salary is more than 4000.
SQL>select ename from emp where sal>4000;
Example 3: Display employee details for employee in ascending order of their salary.
SQL> select * from emp where empid = 10;
TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.
These operations are automatically committed in the database that's why they cannot be used while creating tables or
dropping them.
o
COMMIT o
ROLLBACK o
SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
1. COMMIT;
Example:
b. Rollback: Rollback command is used to undo transactions that have not already been saved to the database.
Syntax:
1. ROLLBACK;
Example:
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire transaction.
Syntax:
1. SAVEPOINT SAVEPOINT_NAME;
Data Control Language(DCL) is used to control privilege in Database. To perform any operation in the
database, such as for creating tables, sequences or views we need privileges. DCL commands are used
to enforce database security in a multiple database environment. Database Administrator's or owners of
the database object can provide/remove privileges on a database object.
DCL defines two commands,
GRANT command:
SQL Grant command is used to provide access on the database objects to the users. The syntax
for the GRANT command is:
GRANT privilege_name ON object_name TO user_name;
Here, privilege_name: is the access right or privilege granted to the user.
object_name: is the name of the database object like table, view etc. user_name: is the
name of the user to whom an access right is being granted.
Revoke Command
The revoke command removes user access rights or privileges to the database objects. The syntax
for the REVOKE command is:
REVOKE privilege_name ON object_name FROM User_name;
Example: (a) SQL>GRANT SELECT ON employee TO user1
This command grants a SELECT permission on employee table to user1.
(b) SQL>REVOKE SELECT ON employee FROM user1
This command will revoke a SELECT privilege on employee table from user1.
• Following are some of the most commonly used constraints available in SQL.
• Constraints can be specified when a table is created with the CREATE TABLE statement or you can
use the ALTER TABLE statement to create constraints even after the table is created.
UNIQUE Constraint –
• UNIQUE constraint ensures that a field or column will only have unique values i.e each value if different
from other values.
Example1: UNIQUE constraint when creating a Table (column level) SQL>CREATE table student
(Rollnum number(3) UNIQUE, Sname char(20), Age number(3));
The above query will declare that the rollnum field of Student table will only have unique
values and won‟t take NULL value.
• A Primary Key must contain unique value and it must not contain null value.
• Usually Primary Key is used to index the data inside the table.
Example3:PRIMARY KEY constraint after table is created (Column Level) ALTER table
student add PRIMARY KEY(rollnum);
The above command will creates a PRIMARY KEY on the rollnum.
FOREIGN Key –
• A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another
table.
• In simpler words, the foreign key is defined in a second table, but it refers to the primary key or a
unique key in the first table.
• The table containing the foreign key is called the child table or detail table, and the table containing
the primary key/candidate key is called parent table or master table.
• The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
• The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the table it points to.
• For example, a table called Customer_Detail has a primary key called c_id. Another table called
Order_ Details has a foreign key which references c_id in order to uniquely identify the relationship
between both tables.
Customer_Detail Table :
Order_Detail Table :
10 Order1 101
11 Order2 103
12 Order3 102
In Customer_Detail table, c_id is the primary key which is set as foreign key in
Order_Detail table. The value that is entered in c_id which is set as foreign key in Order_Detail table
must be present in Customer_Detailtable where it is set as primary key. This prevents invalid data to
be inserted into c_id column of Order_Detailtable.
In this query, c_id in table Order_Detail is made as foriegn key, which is a reference of c_id column of
Customer_Detail.
Example2: FOREIGN KEY constraint at Column Level after creating the table
CHECK Constraint –
• The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn't entered the table.
Dropping Constraints
• Any constraint that you have defined can be dropped using the ALTER TABLE command with the DROP
CONSTRAINT option.
• For example, to drop the primary key constraint in the EMPLOYEES table, you can use the following
command.
Some implementations may provide shortcuts for dropping certain constraints. For example, to
drop the primary key constraint for a table in Oracle, you can use the following command.
SQL Operators:
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to
perform operation(s), such as comparisons and arithmetic operations. These Operators are used to
specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement.
• Arithmetic operators
• Relational operators
• Logical operators
• Special operators
2. Relational Operators:
Checks if the value of left operand is less than the value of (a < b) is
< right operand, if yes then condition becomes true. true.
AND
OR
NOT
The NOT operator reverses the meaning of the logical operator with which it
3 is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate
operator.
ANY
4 The ANY operator is used to compare a value to any applicable value in the
list as per the condition.
BETWEEN
The BETWEEN operator is used to search for values that are within a set of
values, given the minimum value and the maximum value.
6 EXISTS
The EXISTS operator is used to search for the presence of a row in a
specified table that meets a certain criterion.
IN
The IN operator is used to compare a value to a list of literal values that have
7
been specified.
LIKE
The LIKE operator is used to compare a value to similar values using
8
wildcard operators.
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.
VARCHAR2(size) It is used to store variable string data within the predefined length. It can be
VARCHAR(SIZE)
It is the same as VARCHAR2(size). You can also use VARCHAR(size), but it is
suggested to use VARCHAR2(size)
NVARCHAR2(size)
It is used to store Unicode string data within the predefined length. We have to
must specify the size of NVARCHAR2 data type. It can be stored up to 4000 bytes.
Oracle Numeric Data Types
NUMBER(p, s) It contains precision p and scale s. The precision p can range from 1 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.
BINARY_FLOAT It is used for binary precision( 32-bit). It requires 5 bytes, including length byte.
BINARY_DOUBLE
It is used for double binary precision (64-bit). It requires 9 bytes, including length
byte.
Oracle Date and Time Data Types
DATE It is used to store a valid date-time format with a fixed length. Its range varies from
January 1, 4712 BC to December 31, 9999 AD.
TIMESTAMP It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss format.
JOIN EXPRESSIONS :
1. Sql join is used to fetch data from two or more tables, which is joined to appear as single set of data.
2. It is used for combining column from two or more tables by using values common to both tables.
3. Join keyword is used in sql queries for joining two or more tables. minimum required condition for joining table, is (n-1) where
n, is number of tables.
4. A table can also join to itself, which is known as, self join.
Types of join
inner
outer
left
right
This is a simple join in which the result is based on matched data as per the equality condition specified in the sql query.
select column-name-list from table-name1 inner join table-name2 where table-name1.column-name = table-name2.columnname;
example of inner join consider a class table,
id name
1 abhi
2 adam
3 alex
4 anu
and the class_info table,
id address 1
delhi
2 mumbai
3 chennai
inner join query will be, select * from class inner join class_info where
delhi
2 adam 2 mumbai
3 alex 3 chennai
NATURAL JOIN
Natural Join is a type of Inner join which is based on column having same name and same datatype present in both the tables
to be joined.
name2;
1 abhi
2 adam
3 alex
4 anu
and the class_info table,
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
ID NAME Address
1 abhi DELHI
2 adam MUMBAI
3 alex CHENNAI
In the above example, both the tables being joined have ID column(same name and same datatype), hence the records for which value
of ID matches in both the tables will be the result of Natural Join of these two tables.
OUTER JOIN
Outer join is based on both matched and unmatched data. outer joins subdivide further into,
The left outer join returns a resultset table with the matched data from the two tables and then the remaining rows of the left table
and null from the right table's columns.
select column-name-list from table-name1 left outer join table-name2 on table-name1.column-name = table-name2.column-name; to
specify a condition, we use the on keyword with outer join.
left outer join syntax for oracle is,
id name 1 abhi
2 adam
3 alex
4 anu
5 ashish
id address 1
delhi
2 mumbai
3 chennai
7 noida
8 panipat
id name id address
1 abhi 1 delhi
2 adam 2 mumbai
3 alex 3 chennai
4 anu null null
5 ashish null null
RIGHT OUTER
JOIN
The right outer join returns a resultset table with the matched data from the two tables being joined, then the remaining rows of the
right table and null for the remaining left table's columns.
select column-name-list from table-name1 right outer join table-name2 on table-name1.column-name = table-name2.column-name;
id name 1 abhi
2 adam
3 alex
4 anu
5 ashish
id address 1
delhi
2 mumbai
3 chennai
7 noida
8 panipat
id name id address
1 abhi 1 delhi
2 adam 2 mumbai
3 alex 3 chennai
7 null null noida
8 null null panipat
The full outer join returns a resultset table with the matched data of two table then remaining rows of both left table and then the
right table.
select column-name-list from table-name1 full outer join table-name2 on table-name1.column-name = table-name2.column-name;
id name 1
abhi
2 adam
3 alex
4 anu 5 ashish
and the class_info table,
id address 1 delhi
2 mumbai
3 chennai
7 noida
8 panipat
full outer join query will be like,
select * from class full outer join class_info on (class.id = class_info.id);
id name id address 1
abhi 1 delhi
2 adam 2 mumbai
3 alex 3 chennai
4 anu null null 5 ashish null null null null 7 noida null null 8 panipat Built-In Functions
SQL has many built-in functions for performing the calculation of data. SQL provides built-in functions to perform the
operations. Some useful functions of SQL are performing the mathematical calculations, string concatenation and
substring etc.
1. Aggregate Functions
2. Scalar Functions
column.
Scalar functions:
o UCASE(): It converts the database field to uppercase.
displayed.
Aggregate Functions
The aggregate functions return a single value after performing calculations on the group of values. Some of Aggregate
functions are explained below.
AVG Function
AVG () returns the average value of the database after calculating the values in numeric column.
Syntax :
the employees.
COUNT() Function
Count returns the number of rows which are present in the database, and either it is based on the condition or without
condition.
Its basic syntax is,
SQL query to count the number of rows that satisfies the condition.
Output:
Output:
FIRST() Function
Syntax:
SELECT FIRST(column_name) FROM table-name;
Output:
LAST() Function
The LAST function returns the return last value of the selected column.
Output:
MAX() Function
MAX() function returns the maximum value from the selected column of the table.
Syntax:
Output:
MIN() Function
MIN function returns the minimum value of selected column.
SUM() Function
SUM () function returns the total of the specified columns.
Output:
Scalar Functions
Scalar functions return a single value from an input value. Some of the Scalar functions are given below:
UCASE () Function
UCASE () converts the value of the string column into the Uppercase (Capital) characters.
Syntax
Result:
LCASE() Function
LCASE() function is used to convert the value of string columns to Lowercase.
Output:
MID() Function
MID() function is used to extract substrings from column values in the table.
The following SQL query returns the substring start from the second character.
Output:
ROUND() Function
The ROUND() function is used to round a numeric field to a number of the nearest integer. It is used for decimal point.
Syntax:
Output:
Syntax
The basic syntax of the ORDER BY clause is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column
should be in the column-list.
Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in an ascending order by the NAME and the SALARY −
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;