Dbms-Unit 3
Dbms-Unit 3
Table Fundamentals
A table is database object that holds user data. Each column of the table will have a specific data
type bound to it. Oracle ensures that only data , which is identical to the data type of the column
1. Char
2. Varchar /Varchar2
3. Number
4. Date
5. Long
1. CHAR :The CHAR datatype stores fixed-length character strings. When you create a table with
a CHAR column, you must specify a string length (in bytes or characters) between 1 and 2000
bytes for the CHAR column width. The default is 1 byte. Oracle then guarantees that: When you
insert or update a row in the table, the value for the CHAR column has the fixed length.
If you give a shorter value, then the value is blank-padded to the fixed length.
2. VARCHAR2: The VARCHAR2 data type stores variable-length character strings. When you
create a table with a VARCHAR2 column, you specify a maximum string length (in bytes or
characters) between 1 and 4000 bytes for the VARCHAR2 column. For each row, Oracle
Database stores each value in the column as a variable-length field unless a value exceeds the
column's maximum length, in which case Oracle Database returns an error. Using VARCHAR2
For example, assume you declare a column VARCHAR2 with a maximum size of 50
characters. In a single-byte character set, if only 10 characters are given for the VARCHAR2
column value in a particular row, the column in the row's row piece stores only the 10
characters.
3. NUMBER(P,S): The NUMBER datatype stores fixed and floating-point numbers. They are upto
38 digits of precision. For numeric columns, you can specify the column as: column_name
NUMBER
Optionally, number can also specify a precision (total number of digits) and scale (number of
digits to the right of the decimal point): column_name NUMBER (precision, scale)
If a precision is not specified, the column stores values as given. If no scale is specified, the scale
is zero.
4. DATE: The DATE datatype stores point-in-time values (dates and times) in a table. The DATE
datatype stores the year (including the century), the month, the day, the hours, the minutes, and
the seconds (after midnight). For input and output of dates, the standard Oracle date format is
5. LONG: This data type is used to store variable length character strings containing upto 2
GB.LONG data can be used to store arrays of binary data in ASCII format.
The CREATE TABLE statement is used to create a new table in the database.
This command defines each column of the table uniquely . Each column has a minimum of three
attributes a name, datatype and size. Each column has a specific data type which specifies how
data is stored in the column. Each column definition is separated from the other by a comma and
Syntax:
….
Example:
a. Create a table called student that contains roll number, name and marks in three subjects
(rollno number(2),
name varchar2(20),
m1 number(2),
m2 number(2),
m3 number(2));
Table created.
INSERT: The INSERT statement is used to insert records into a table. This statement loads the
table with data to be manipulated later. When inserting a single row into the table the insert
Syntax:
Example:
Method 1
SQL> insert into student(rollno,name,m1,m2,m3) values (11,'Rama',65,75,50);
1 row created.
Method 2
SQL> insert into student values(&rollno,'&name',&m1,&m2,&m3);
Enter value for rollno: 12
1 row created.
Method 3
1 row created
SELECT : Once data is inserted into the tables, the next logical operation would be to view the
data that has been inserted. The SELECT verb in SQL is used to achieve this. The SELECT
Syntax:
The DISTINCT clause in the select statement allows removing of duplicate rows
from the result set. The DISTINCT clause can only be used with select statements. It
scans through the values in the columns specified and displays only unique values
amongst them.
Example:
ROLLNO NAME M1 M2 M3
11 Raja 50 60 70
12 Rama 70 80 75
13 John 45 55 65
14 Gita 40 50 45
15 Tom 30 35 25
5 rows selected
ROLLNO NAME
---------- --------------------
11 Raja
12 Rama
13 John
14 Gita
15 Tom
5 rows selected
ROLLNO NAME M1 M2 M3
11 Raja 50 60 70
12 Rama 70 80 75
2 rows selected
d. Display names of students who secured more than 50 either in subject1 or subject 3
NAME
--------------------
Raja
Rama
John
3 rows selected
COURSE
-----
BCA
BBM
MCA
3 rows selected
The rows retrieved from the table will be sorted in ascending 0r descending order on the
condition specified .
Syntax:
order]>;
Example:
ROLLNO NAME M1 M2 M3
11 Raja 50 60 70
12 Rama 70 80 75
13 John 45 55 65
14 Gita 40 50 45
15 Tom 30 35 25
5 rows selected
We can create a table from another table in SQL. The syntax is as follows
Example:
a. Create a table named sample from the existing table student that contains only rollno and
names of students
Table created.
b. Create a table named sample1 that contains the same structure as student but with no records
Table created.
no rows selected
Syntax:
<TableName>;
Syntax:
DELETE: The DELETE command is used to delete rows from a table that satisfies the condition
and returns the number of records that were deleted. If the DELETE command is executed
Syntax:
Example:
ROLLNO NAME
---------- --------------------
11 Raja
12 Rama
13 John
14 Gita
15 Tom
5 rows selected
5 rows deleted.
1 row deleted.
UPDATE: The UPDATE command is used to change or modify data values in a table. The
UPDATE in SQL is used to either update all the rows or selected rows in a table. The UPDATE
statement updates columns in the existing table’s rows with new values. The SET clause
indicates which column data should be modified and the new values they should hold. The
WHERE clause, if given, specifies which rows should be updated. Otherwise all the rows are
updated.
Syntax:
<expression>WHERE <condition>;
Example:
4 rows updated.
4 rows updated.
1 row updated.
ALTER: The structure of a table can be modified by using the ALTER TABLE command. ALTER
TABLE allows the user to change the structure of the existing table. With ALTER TABLE
command it is possible to
ALTER TABLE works by making a temporary copy of the original table. The alteration is
performed on the copy, then original table is deleted and the new one is modified.
Syntax:
Example:
a. Add a new column Total with data type number and size 2
Table altered.
Table altered.
Renaming tables
RENAME
RENAME command is used to rename or give another name to the existing table.
Syntax:
Example:
Table renamed.
DESTROYING TABLES: The DROP TABLE statement is used to destroy a specific table. If a table
is dropped all the records held within it are lost can cannot be recovered.
Syntax:
Example:
Table dropped.
DESCRIBE: The DESCRIBE command is used to display the structure of a table. This command
displays the column names, the data types and the special attributes that are connected to the
table.
Syntax:
Example:
------------------------------------------------- ----------------------------
ROLLNO NUMBER(2)
NAME VARCHAR2(20)
M1 NUMBER(2)
M2 NUMBER(2)
M3 NUMBER(2)
TOTAL NUMBER(3)
There are two types of data constraints that can be applied to data being inserted into an oracle
table. One type of constraint is the I/O constraint that determines the speed at which data can
be inserted or extracted from a table. The other type of constraint is called the business rule
constraint.
i) Primary key constraint – A primary key is one or more columns in a table use to uniquely
identify rows in a table. None of the fields that are a part of primary key can contain null values.
A table can have only one primary key. The data in that column should be unique i.e. no
duplicate values are allowed. The column is a mandatory column i.e. it cannot be left blank and
NOT NULL attribute A Single column key is called a simple key. A multicolumn key is called a
Syntax :
ii) Foreign key constraint – Foreign keys represent relationship between tables. A foreign key
is a column whose values are derived from primary key of some other tables. The table in which
the foreign key is defined is called foreign table. The table in which the primary key is defined
is called the primary table or master table. The master table can be referenced in the foreign
At column Level:
Syntax :
<ColumnName><Datatype>(<size>)
At table level:
[(<ColumnName>),<ColumnName>)
Oracle displays an error message when the record in the master table is deleted and
corresponding records exists in the foreign table. It prevents the delete operation to be
performed. For this reason, Oracle provides ON DELETE CASCADE option. If the ON DELETE
CASCADE option is set, a delete operation in the master table will trigger a DELETE operation
A constraint can be given a user-defined name by preceding the constraint defined with the
Syntax:
<ColumnName><Datatype>(<size)UNIQUE
(<ColumnName1>,<ColumnName2>));
Oracle allows programmers to define constraints at table level and column level. If the
constraints are defined as an attribute of a column definition when creating or altering the table
structure, they are column level constraints. If data constraints are defined after defining all the
table column attributes when creating or altering a table structure, then it is table level
i. NOT NULL – A NULL is different from zero or blank. A NULL value can be inserted into
columns of any data type. The NOT NULL constraint ensures that a table column cannot
be left empty. When a column is defined as NOT NULL, then that column becomes
mandatory. It implies that a value must be entered into the column if that record is to be
ii. CHECK constraint – This constraint must be specified as a logical expression that
evaluates either to a TRUE or FALSE. E.g. Data values being inserted to begin with a
uppercase.
Syntax:
check(logical expression)
Example:
Create a table EMPLOYEE using SQL command to store details of employees such as EMPNO,
NAME, DESIGNATION, DEPARTMENT, GENDER and SALARY. Specify Primary Key and NOT
NULL constraints on the table and allow only ‘M’ or ‘F’ for the column GENDER. Write the
dept varchar2(20),
gender char(1),
Table created.
A table can be created with multiple constraints attached to its columns. The user can
view the structure along with its constraints using the DESCRIBE command. This command only
displays the column names, data type, size and not null constraints. The information about other
constraints like primary key, foreign key is not available using the describe command. Oracle
Integrity constraints can be applied to tables using the ALTER table command.
Example:
Table altered.
b. Show that the above constraint has been applied using USER CONSTRAINTS table
table_name='STUDENT';
OWNER TABLE_NAME C
------------------------------ ------------------------------ -
SCOTT STUDENT P
Integrity constraints can be dropped if the constraint is no longer needed. This can be achieved
Example:
Table altered.
Default values can be assigned to columns when we create a table. When a record is
loaded into the table and a column is left empty, oracle engine will automatically load this
column with the default value specified. The data type of the default value must match with the
Syntax:
Arithmetic Operators
Oracle allows arithmetic operators to be used while viewing records from a table or
while performing data manipulation operations. The various arithmetic operators are as follows
Operator Meaning
+ Addition
- Subtraction
/ Division
* Multiplication
** Exponentiation
Comparison Operators
Comparison operators are used to compare the column data with specific values in a condition.
Comparison Operators are also used along with the SELECT statement to filter data based on
specific conditions.
Operators Description
= equal to
Examples:
a. List the roll number and names student whose total is more than 200
SQL> select rollno,name from student where total>200;
ROLLNO NAME
12 Sriram
17 Shyam
2 rows selected
NAME
John
Gita
Tom
3 rows selected
c. List the names of students who got more than or equal to 70 in subject3
NAME
Sriram
Shyam
2 rows selected
Logical operators :There are three Logical Operators namely, AND, OR, and NOT. These
operators compare two conditions at a time to determine whether a row can be selected for the
output. Logical operators are used in the WHERE clause and allows you to combine more than
one condition.
OR For the row to be selected at least one of the conditions must be true.
AND For a row to be selected all the specified conditions must be true.
Example:
a. List the details of students who secured more than 60 in subject 1 and subject 2
1 row selected
b. List the names of students who secured less than 50 in any subject
NAME
John
Gita
Tom
3 rows selected
Range Searching
In order to select data that is within a range of values, the BETWEEN operator is used.
The BETWEEN operator allows the selection of rows that contain values within a specified
lower and upper limit. The two values in between the range must be linked with a keyword
AND. The BETWEEN operator can be used with both character and numeric data types.
Example:
a. List the names of students whose total is in the range 180 and 250
SQL> select * from student where total between 180 and 250;
2 rows selected
BCA III SEM Page 20
DATABASE MANAGEMENT SYSTEM Unit 2
Pattern Matching
The LIKE operator is used to list all rows in a table whose column values match a
specified pattern. It is useful when you want to search rows to match a specific pattern, or when
you do not know the entire value. For this purpose we use a the following wildcard character
Example:
NAME
--------------------
Sriram
Sita
Shyam
3 rows selected
b. List the name and roll number of students whose name ends with ‘a’
ROLLNO NAME
14 Gita
16 Sita
2 rows selected
c. List the names of students who have ‘i’ as the second letter in their name.
NAME
--------------------
Gita
Sita
2 rows selected
d. List the course whose name ends with the letter ‘m’
COURSE
bbm
bbm
2 rows selected
The arithmetic operator (=) compares a single value to another single value. In case a value
needs to be compared to a list of values then the IN predicate is used. It reduces the need to use
Example:
a. List the student names and course who are studying either MCA OR BCA
NAME COURSE
Sriram BCA
Gita BCA
Sita MCA
Tom MCA
4 rows selected
b. List the student names along with their course who are not studying MCA
SQL> select name, course from student where course not in ('mca')
NAME COURSE
Sriram BCA
John BBM
Gita BCA
Shyam BBM
4 rows selected
Dual is a table owned by SYS. SYS owns the data dictionary and DUAL is a part of data
dictionary. Dual is a small Oracle work table which consists of only one row and one column. It
contains the value x in that column. It is used to perform small arithmetic calculations and also
DUMMY VARCHAR2(1)
DUAL
Example:
3*5
----------
15
SYSDATE is a pseudo column that contains the current date and time. It requires no arguments
when selected from the table DUAL and returns the current date.
Example:
SYSDATE
--------------
18-NOV-15
Oracle Functions: Oracle functions serve the purpose of manipulating data items and returning
the result. Functions are also capable of accepting user-supplied variables or values and
operating on them. Such variables are called arguments. The general format of a function is
Function_name(argument1, argument2,….)
Oracle functions can be classified depending on whether they operate on a single row or
Functions that act on a set of values are called group functions. A group function returns
a single result row for a group of queried rows. A list of group functions with examples is given
below.
Examples:
Syntax: AVG([<DISTINCT>|<ALL>]<n>)
Average
----------
171.666667
Syntax: MAX([<DISTINCT>|<ALL>]<expr>)
Maximum Total
--------------------
235
Syntax: MIN([<DISTINCT>|<ALL>]<expr>)
Minimum Total
-------------------
100
4. COUNT (*)– Returns the number of rows in a table, including duplicates & nulls
Syntax: COUNT(*)
COUNT(*)
--------------
5. COUNT (expr )– Returns the number of rows where expr is not null
E.g. Display the sum total of marks in subject1 from student table
Marks in Subject1
-----------------
295
Functions that act only on one value at a time are called scalar functions. A single row
function returns one result for every row of a queried table. They can further be grouped
depending on the data type of value upon which they act. The classification of scalar functions is
as follows:
String Functions:
String functions are used to manipulate text strings. They accept strings or characters as
input and can return both character and number values as output.
LTRIM (string_value, trim_text) All occurrences of 'trim_text' is removed from the left of
'string_value'.
RTRIM (string_value, trim_text) All occurrences of 'trim_text' is removed from the right
of 'string_value' .
TRIM (trim_text FROM All occurrences of 'trim_text' from the left and right of
'string_value' , 'trim_text' can also be only one character
string_value)
long .
SUBSTR (string_value, m, n) Returns 'n' number of characters from 'string_value'
Examples:
Numeric functions are used to perform operations on numbers. They accept numeric
values as input and return numeric values as output. Few of the Numeric functions are:
ROUND (x, y) Rounded off value of the number 'x' up to the number 'y'
decimal places
CEIL (x) Integer value that is Greater than or equal to the number 'x'
FLOOR (x) Integer value that is Less than or equal to the number 'x'
The following examples explains the usage of the above numeric functions
TRUNC(38.546,2)
38.54
The DATE data type is used to store date & time information
If data from a date column has to viewed in any other format then
Syntax: TO_DATE(char[,fmt])
Date Functions:
These functions are used to manipulate and extract values from the date column of a table
Function Name Return Value
ADD_MONTH
25-DEC-13
Conversion Functions:
These are functions that help us to convert a value in one form to another form. For
example, a null value into an actual value, or a value from one datatype to another datatype like
NVL, TO_CHAR, TO_NUMBER, TO_DATE.
Function Name Return Value
TO_CHAR(SYSDATE,'
25-september-2013
TO_DATE('
15-AUG-47
The GROUP BY clause tells Oracle to group rows based on distinct values that exists from
specified columns. The group by clause creates a data set containing several sets of records
Syntax:
AGGREGATE FUNCTION(Expression)
Example:
SQL> select course, count(*) "Number of Students" from student group by course;
BCA 2
BBM 2
MCA 2
3 rows selected
COURSE MAX(TOTAL)
----- ----------
BCA 235
BBM 210
MCA 165
3 rows selected
Having clause
The HAVING clause is used in conjunction with the group by clause. It imposes a
condition on the group by clause, which further filters the groups created by the group by
clause. Each column specification specified in the having clause must occur in the list of columns
Example:
COURSE
BCA
MCA
the HAVING clause can be used to find unique values in situations to which DISTINCT does not
apply the DISTINCT clause eliminates duplicates,but does not show which values actually were
duplicated in the original data the HAVING clause can identify which values were unique or
non-unique
ORDER BY Clause: The ORDER BY clause is used in a SELECT statement to sort results either in
ascending or descending order. Oracle sorts query results in ascending order by default.
Syntax:
SELECT column-list
Example:
NAME TOTAL
-------------------- ----------
Tom 100
Gita 145
Sita 165
Shyam 210
Sriram 235
5 rows selected
NAME M1
-------------------- ----------
Sriram 70
Shyam 60
Sita 50
Gita 40
Tom 30
5 rows selected
Sub Queries
A subquery is a form of SQL statement that appears inside another SQL statement. It is
also called a nested query. The statement containing the subquery is called parent query. The
parent statement uses the result set returned by the subquery. It can be used for
To provide values for conditions in the WHERE, HAVING, IN clause used with SELECT,
The concept of using a subquery in the FROM clause of the SELECT statement is called inline
view.
A correlated subquery is one where a subquery references a column from a table in the
parent query. A correlated subquery is evaluated once for each row of the parent statement,
The EXISTS operator is usually used with correlated subqueries. This operator enables to
test whether a value retrieved by the outer query exists in the result set of the values retrieved
by the inner query. If the subquery returns at least one row, the operator returns true. If the
value does not exist, it returns false. The EXISTS operator ensures that the search in the inner
query terminates when at least one match is found. The NOT EXISTS operator enables to test
whether a value retrieved by the outer query is not a part of the result set of the values retrieved
Examples:
6 rows selected.
4 rows selected
SQL> select ename from employ where deptno in (select dno from depart where
loc='chennai');
ENAME
---------------
Rani
Ranbir
2 rows selected
SQL> select loc from depart where dno=(select deptno from employ where
ename='Sita');
LOC
---------------
Bangalore
c. List the employee number, employee name, salary and average salary of the department
whose salary is more than the average salary in the department(inline view)
d. List the employee names, salary who are drawing maximum salary in each department
(correlated subquery)
SQL> select ename,deptno,sal from employ a where sal = (select max(sal) from employ
where deptno=a.deptno);
SQL> select dno,dname from depart a where not exists(select deptno from employ
where deptno=a.dno);
DNO DNAME
---- ---------------
D005 inventory
SQL> select ename from employ a where exists (select dname from depart where
ENAME
---------------
Ranbir
Rani
Joins
There are occasions where we need to retrieve data from multiple tables. This is achieved
in SQL using joins. Tables are joined on columns that have same data type and data width in the
tables. The tables are related with the help of primary key and foreign keys of the table. The
1) INNER JOIN
2) OUTER JOIN
3) CROSS JOIN
4) SELF JOIN
1) INNER JOIN – These joins are also called equi joins. They are known as equi joins because the
where clause compares two columns using the = operator. It is the most commonly used
operator. It returns all the rows from both the tables where there is a match.
Example:
a. Display the names of employees and the department in which they work
ENAME DNAME
--------------- ---------------
Raja research
Rani accounts
Jaya HRD
Ranbir accounts
Rajni EDP
Sita HRD
6 rows selected.
and dname='HRD';
ENAME
---------------
Jaya
Sita
2) OUTER JOIN – This type of join can be used in selecting rows from both the tables regardless
of whether the tables have common values or not. NULL values are appended in the result set
where the data is missing. For left outer join use a (+) to the left condition and for right outer
WHERE t1.column(+)=t2.column;
WHERE t1.column=t2.column(+);
Example:
a. Display the employee name and department using left outer join
ENAME DNAME
--------------- ---------------
Raja research
Rani accounts
Jaya HRD
Ranbir accounts
Rajni EDP
Sita HRD
6 rows selected.
b. Display the employee name and department using right outer join
ENAME DNAME
--------------- ---------------
Ranbir accounts
Rani accounts
Raja research
Sita HRD
Jaya HRD
Rajni EDP
6 rows selected.
3) CROSS JOIN – A cross join returns the Cartesian product. This means that the join combines
every row from the left table with every row in the right table.
ENO ENAME
---- ----------
E001 janani
E002 jahnavi
PNO PNAME
---- -- --------
P001 soap
P002 shampoo
4) SELF JOIN – A self-join is one where the same table is involved in the join operation
Example:
a. Display the employee names and salary who earn more than Sita
SQL> select e1.ename,e1.sal from employ e1, employ e2* where (e1.sal>e2.sal) and
(e2.ename='Sita');
ENAME SAL
--------------- ----------
Raja 6000
Rani 7000
Ranbir 8000
Union Clause:
Multiple queries can be put together and their output can be combined using the union
clause. The union clause merges the output of two or more queries into a single set of rows.
Here, the number of columns and the data type of the columns must the same in all the select
Intersect Clause:
Multiple queries can be put together and their output can be combined using the
intersect clause. It outputs only the rows produced by both the queries intersected. The output
in the intersect clause will include only those rows that are retrieved common to both the
queries. Here, the number of columns and the data type of the columns must the same in all the
Minus Clause:
Multiple queries can be put together and their output can be combined using the minus
clause. The minus clause outputs the rows produced by the first query, after filtering the rows
retrieved by the second query. Here, the number of columns and the data type of the columns
must the same in all the select statements used in the query.