DBMS Unit Iv
DBMS Unit Iv
Introduction
for querying, altering and defining relational databases, using declarative statements.
SQL is pronounced /ˌɛs kjuː ˈɛl / (letter by letter) or /ˈsiːkwəl / (as a word).
Some of the popular relational database example are Oracle, MySQL, MSSQL, MariaDB,
PostgreSQL etc.
SQL is used to perform C.R.U.D (Create, Retrieve, Update & Delete) operations on
relational databases.
SQL can also perform administrative tasks on database such as database security,
backup, user management etc.
― It can
SQL Datatypes
Data types are used to represent the nature of the data that can be
stored in the database table. For example, in a particular column of a table, if we want
to store set of characters then data type of this column should be character. Data types
2. Numeric Types
Character Types
CHAR(SIZE) It is used to store character data. It can be stored up to 2000 bytes.
It is used to store variable string data. It can be stored up to 4000
VARCHAR2(SIZE)
bytes.
It is the same as VARCHAR2(size). but it is suggested to use
VARCHAR(SIZE)
VARCHAR2(size)
It contains precision p and scale s. The precision p can range from 1
NUMBER(p, s)
Numeric
Types
SQL Commands
SQL commands are instructions. They are used to communicate with the
database. They can perform various tasks like create a table, add data to tables, drop
the table, modify the table, set permission for users.
1. DDL Commands
sequences, synonyms, etc., All the DDL statements are auto committed that means it
permanently saves all the changes in the database. Commands that come under DDL:
1. CREATE
2. ALTER
3. DROP
4. TRUNCATE
5. RENAME
1. 1 Create: Create is used for creating the database or its objects (Ex: table, view,
index, function, store procedure and triggers).
It is used to create tables in the database. The table gets created as soon as the
CREATE TABLE script is executed and is ready to hold the data and its syntax is:
create table <table-name> (
column1 data_type (size) column_constraint,
column2 data_type (size) column_constraint,
.
.
.
columnN data_type (size) column_constraint,
table_constraint
);
In this syntax:
includes the column name followed by data type and its size and a column
check.
Example: The following example shows how to create a new table named student
DESCRIBE is most often used to view the definition of a table or a view. It gives
you a list of columns in the table or view, along with its datatypes, lengths, and
nullability. Enter the command DESC followed by the name of the table or view you
are interested in, as the following example shows:
desc student;
Column Null? Type
--------------------- ------ ----------------
ROLLNO - NUMBER(2,0)
SNAME - VARCHAR2(20)
GENDER - CHAR(5)
CGPA - NUMBER(5,2)
ALTER TABLE is used to change the table structure or column definitions after the table
has been created in the database. It is used to add, drop, rename, and modify a
on the table.
Example:
We will use the student table that we created previously to demonstrate ALTER TABLE
Statement.
For example, to add new column named dob to the student table:
alter table student add dob date;
Now dob column is appended at the end of the column list; you can view this by
To add multiple columns, place the new columns inside the parenthesis separated
by commas as follows:
alter table <table-name> add (
column_name data-type(size) constraint,
column_name data-type(size) constraint,
...
);
Example:
alter table student add (
phone VARCHAR(20),
email VARCHAR(100)
);
Above statement adds two new columns named phone and email to the student
table.
should be empty. Use the following syntax to modify the column properties:
For example, the following statement changes the phone column datatype to
Use desc command to view the changes. To modify multiple columns, place the
Example:
alter table student rename column rollno to sid;
dropped table and its data remain no longer available for selection. Dropped table can
the index and triggers associated with it. Its syntax is:
Example 1: The below statement will drop the table and place it into the recyclebin.
drop table student;
Example 2: The below statement will drop the table and flush it out from the
recyclebin also.
drop table student purge;
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the
table itself and its syntax is:
truncate table <table_name>;
Example:
truncate table student;
Now, the STUDENT table is truncated and the output from SELECT statement will be
as shown like −
1. 5 RENAME Statement
RENAME table statement to rename an existing table in the database and
Example:
rename student to std;
2. DML Statements
Commands that modify data are called data manipulation language commands.
Ch. Vijayananda Ratnam@Dept. of CSE 7
Database Management Systems UNIT-IV
2.1 INSERT: An INSERT statement is used to add new rows of data to a table and its
syntax is:
insert into <table_name> (column_list) values(value_list);
• First, specify the name of the table into which you want to insert.
• Second, specify a list of comma-separated column names within parentheses.
list.
• Character type values are always enclosed in single quotes; number values are
never in quotes;
• Date values are often (but not always) in the format ‘dd-mm-yyyy’ (for
example, ’12-06-2016’).
If the value list has the same order as the table columns, you can skip the column list
insert into table_name values (value_list);
Example 1: Let us create student table once again and try insert data into it by using
insert statement:
create table student (
rollno number(3),
sname varchar2(15),
cgpa number(5,2),
dob date);
(or)
insert into student values (501,'Akshara',87.5, to_date('15-10-2002','dd-
mm-yyyy'));
After you execute the INSERT statement, the message “1 row(s) inserted” is displayed,
indicating that data has been inserted in the table. To verify that the row was added,
The following statements insert new rows into the student table:
2.2 UPDATE: It is used to change the existing rows in a table and its syntax is:
This would update the sname to ‘Raju' and cgpa to 86.5 where the rollno is 510. You
This would update all the rows of cgpa to 76.5. You can check it by executing
select * from student;
ROLLNO SNAME CGPA DOB
------- --------- ------- ---------
501 Akshara 76.5 15-10-12
555 Yaswanth 76.5 05-05-01
517 Krishna 76.5 05-07-00
510 Raju 76.5 18-12-01
526 Chaitanya 76.5 09-07-01
2.3 DELETE: Delete statement used to delete one or more rows from a table and its
syntax is:
DELETE FROM <table_name> WHERE condition;
In this statement,
• First, you specify the name of the table from which you want to delete data.
• Second, the optional WHERE clause determines which rows of the table should
be deleted. If you omit it, the DELETE statement will remove all rows from the
table.
2. 4 SELECT
Most of the SQL operations performed on a database in a typical organization
are SELECT statements, which enable users to retrieve data from tables. In essence,
the SELECT statement asks the database a question, that’s why it’s also known as a
query.
The syntax for an SQL statement is the basic structure, or rules, required to
execute the statement. Below shows the syntax for the SELECT statement.
In this statement:
Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any violation
between the constraint and the data action, the action is aborted. So, constraints are
created to protect the integrity of the data and improve the quality of the data.
Constraints can be column level or table level. Column level constraints apply to
a column, and table level constraints apply to the whole table.
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement.
This enforces a field to always contain a value, which means that you cannot insert a
new record, or update a record without adding a value to this field.
The NOT NULL constraints are inline constraints which are typically used in the column
definition of the CREATE TABLE statement.
EXAMPLE:
create table student (
sno number,
sname varchar2(20) constraint nn_sname NOT NULL
);
It is also possible to add a NOT NULL constraint to an existing table by using the ALTER
TABLE statement.
Syntax:
alter table <table-name> modify (column_name NOT NULL);
Example:
alter table student modify sname not null;
Below insert statement will validate the above not null constraint.
insert into student values(1,null);
2. UNIQUE Constraint
The UNIQUE constraint ensures that values stored in a column or group of columns are
different or NULL values.
They could be added to the table as inline (column level) and out-of-line(table level).
In the above statement, for both columns will have one constraint or you can also create
two separate statements like
It is also possible to add a UNIQUE constraint to an existing table by using the ALTER
TABLE statement.
Syntax:
alter table <table-name> add constraint constraint_name
constraint_type(col_1, ..., col_N);
Example:
alter table student add constraint unq_sno unique(sno);
*
ERROR at line 1:
ORA-00001: unique constraint (UNQ_SNO) violated.
The primary key column should be filled and allows only unique values. A table can
have only ONE primary key and it can be created for composite (Two or more columns) keys
also.
In the above statement primary key is called as composite primary key since it is a
combination of two columns.
It is also possible to add a PRIMARY KEY constraint to an existing table by using the
alter table statement.
Example:
alter table student add constraint pk_sno primary key(sno);
Below insert statements will validate the above PRIMARY KEY constraint.
insert into student values(1, null);
insert into student values(1, null); //duplicate value is not allowed.
*
ERROR at line 1:
ORA-00001: unique constraint (PK_SNO) violated.
4. CHECK Constraint
The CHECK constraint is used to limit the values that can be placed in a column.
If you define a CHECK constraint on a column it will allows only certain values for this
column.
Note: for table level refer the general table – level syntax.
Example:
create table student
(
sid integer,
sname varchar2(20),
gender char(1) constraint chk_gen check( gender in ('M','F'))
);
For gender column, it allows only ‘M’ and ‘F’ values other than these values will be
rejected.
PL/SQL
An exception is a PL/SQL error that is raised during program execution, either implicitly
or explicitly by your program. The exceptions can have different causes such as coding
mistakes, bugs, even hardware failures.
It is not possible to anticipate all potential exceptions, however, you can write code to
handle exceptions to enable the program to continue running as normal.
The code that you write to handle exceptions is called an exception handler.
PL/SQL Exception message consists of three parts.
1. Type of Exception
2. An Error Code
3. A message
By handling the exceptions, we can ensure a PL/SQL block does not exit abruptly. Here
is the basic syntax of the exception-handling section:
Ch. Vijayananda Ratnam@Dept. of CSE 17
Database Management Systems UNIT-IV
BEGIN
-- executable section
...
-- exception-handling section
EXCEPTION
WHEN e1 THEN
-- exception_handler1
WHEN e2 THEN
-- exception_handler1
WHEN OTHERS THEN
-- other_exception_handler
END;
/
In this syntax, e1, e2 are exceptions. When an exception occurs in the executable
section, the execution of the current block stops and control transfers to the exception-
handling section.
Example
Let us understand with help of EMP table we had created and used previously.
DECLARE
e_id emp.empno%type :=&e_id;
e_name emp.ename%type;
e_design emp.job%type;
BEGIN
SELECT ename, job INTO e_name, e_design FROM emp
WHERE empno = e_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| e_name);
DBMS_OUTPUT.PUT_LINE ('Designation: ' || e_design);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such employee!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result
No such employee!
Types of exceptions
1. Pre-defined Exceptions
2. User-defined Exceptions
Pre-defined Exceptions
no rows.
PL/SQL declares predefined exceptions globally in package STANDARD, which
defines the PL/SQL environment. So, you need not declare them yourself. You can write
handlers for predefined exceptions using the names in the following list: