DBMS Package For Class Project: 13.1 Data Types in Oracle
DBMS Package For Class Project: 13.1 Data Types in Oracle
All database System store the user data in the form of a table. A table is
really a two dimensional matrix that consist of rows and columns. Each
column consists a cell, cell is also called a field. A no. of field placed in
horizontal row is called a record. By creating record and then table, the
user can store and maintain data. This chapter is concerned with the way
by which any user can create and manipulate the data.
1. CREATE TABLE
Syntax: CREATE TABLE tablename (Columname datatype(size),
column name datatype(size); Example
0
For Example:
client_no Varchar 2 6
name Varchar 2 20
address Varchar 2 30
city Varchar 2 15
state Varchar 2 15
pincode number 6
1
Profit_percent Number 2, 2
Unit_measure` Varchar 2 10
Qty_on_hand Number 8
Sell_price Number 8, 2
Cost_price Number 8, 2
Syntax:
tablename;
For Example:
2
2. ALTER TABLE
Syntax:
ALTER TABLE existing_table_name MODIFY (columnname
newdatatype(size));
For Example:
And if we have an EMP table with EmpNo as a one filed in the table and we want to add
primary key constraint on EmpNo then we use ALTER command as following way:
3. DROP TABLE
This command deletes table structure and cannot be recovered.
For Example:
4. TRUNCATE TABLE
1. INSERT
This command is used for inserting data into table.
3
Syntax: INSERT INTO tablename VALUES (value1,value2, …….);
SQL>Insert into Client_master Values ('CN2001', 'Deepak Kumar', 'A-5, Patel Nagar',
'Rohtak', 'Haryana',134001,50000);
SQL>Insert into Client_master Values ('CN2002', 'Naresh Kumar', '618, Sec- 15', 'Gurgaon',
'Haryana',132001,25000);
Syntax:
INSERT INTO tablename (c1,c2, .... ) SELECT columnname, columnname, .... FROM tablename;
Other Examples:
1 row created
1 row created
2. UPDATE
4
Syntax: UPDATE tablename SET columnname =value [WHERE condition];
For Examples:
3. DELETE
For Examples:
1. COMMIT Command
The COMMIT command executes a SQL COMMIT command and save
changes for permanent use.
Syntax:
COMMIT;
SQL>commit;
Commit complete.
5
2. ROLLBACK Command
This command is used for undo, work done by last command or transaction.
Syntax:
1. ROLLBACK TO SAVEPOINT text_identifier;
2. ROLLBACK;
SQL>rollback;
Rollback complete
3. SAVEPOINT
Syntax:
SAVEPOINT text_identifier;
Example:
a) UPDATE emp
SET salary = 95000
WHERE emp_id=101;
SAVEPOINT t1;
UPDATE emp
SET salary = 100000;
SAVEPOINT t2;
COMMIT;
b) SQL>SAVEPOINT t3;
SQL>delete test;
2 rows deleted.
Rollback complete.
6
13.5 ORDER BY, GROUP BY, HAVING clause and DISTINCT keyword
Order by: The order by clause is used to display the results in sorted order i.e. ascending by
keyword asc or descending by keyword desc. By default output displays in ascending order.
For example:
Output:
ID NAME
---------- ---------------
2 saini
1 alka
Output:
ID NAME
---------- ---------------
1 alka
2 saini
Group by: This clause is used along with the SQL aggregate functions like SUM to provide
means of grouping the result. Tuples with the same value on all attributes in the group by
clause are placed in one group.
ID NAME
---------- ---------------
1 alka
2 saini
7
3 alka
4 alka
4 alka
Having: This clause is used in SQL because the WHERE clause could not be used with
aggregate functions. SQL applies conditions in the having clause after groups have been
formed, so aggregate function be used.
For Example:
SQL> select name, sum(id) from s2 group by name having sum(id) >4;
NAME SUM(ID)
--------------- ----------
alka 13
SQL> select name, sum(id) from s2 group by name having sum(id) < 4;
NAME SUM(ID)
--------------- ----------
saini 2
DISTINCT keyword
In a table, some of the columns may contain duplicate values. And if you want to display
only the different or distinct values from the table, then we use the DISTINCT keyword with
the select clause.
For example:
8
Primary Key: A primary key constraints is a unique identifier for a row with
in a database table. Primary key values cannot be null and must be unique
across the column.
For Example:
Column level constraint: Applied only at one column at a time along with column
definition.
SQL>Create table student (RollNo number(6) PRIMARY KEY, SName varchar2(15),
Class varchar2(15), Department varchar2(15));
Table level constraint: Mostly table level constraint is used for multiple column constraint.
SQL>Create table student1 (RollNo number(6), SName varchar2(15), Class varchar2(15),
Department varchar2(15), Mobile varchar2(10), PRIMARY KEY(RollNo,Mobile));
Foreign Key: A foreign key constraints is a key used to link two tables
together. A foreign key in one table points to a primary key in another table.
For Example:
9
ALTER TABLE tablename DROP CONSTRAINT foreignkeyname ;
e.g. SQL> ALTER TABLE Marks1 DROP CONSTRAINT fk;
For Example:
Null Value Constraint: A NOT NULL constraint enforces that the column
will not accept null values. When a column becomes NOT NULL, then it
becomes mandatory.
For Example:
SQL>Create table Test3 (ID varchar2(6) NOT NULL, name varchar2(15), address
varchar2(30), city varchar2(15));
For Example:
SQL>Create table Test6 (ID varchar2(6), name varchar2(15), address varchar2(30), city
varchar2(15), CONSTRAINT cnk CHECK (name like ‘S%’));
10
DEFAULT Value Constraint: This type of constraint is used when no value is
supplied to particular column.
For Example:
SQL>Create table Test7 (ID varchar2(6) PRIMARY KEY, name varchar2(15), address
varchar2(30) DEFAULT ‘Gurgaon’, city varchar2(15));
1. AVG() Function
The AVG() function returns the average value of a numeric filed.
Syntax: AVG(filedname)
Example:
2. COUNT() Function
This function returns the number of values and NULL values are not counted by this
function.
Syntax: COUNT(filedname)
Example:
3. MAX() Function
This function returns the largest value of the selected column.
11
Syntax: MAX(filedname)
Example:
4. MIN() Function
This function returns the smallest value of the selected column.
Syntax: MIN(filedname)
Example:
5. SUM() Function
This function returns the total sum of a column but column must be numeric.
Syntax: SUM(filedname)
Example:
6. UPPER() Function
This function converts the value of a field to uppercase.
Example:
7. LOWER () Function
This function converts the value of a field to lowercase.
12
Syntax: LOWER (filedname)
Example:
8. LENGTH() Function
This function returns the length of the value in a text field.
Example:
LENGTH('DBMS')
--------------
4
9. SQRT() Function
This function returns the square root of the specified field or numeric expression.
Example:
13
Syntax: ABS (number)
Example:
Example:
Output:
ROUND(19.79,1)
--------------
19.8
This function returns the number raised to nth power, both the value must be numeric.
Example:
Output:
POWER(5,2)
----------
25
14
13. INITCAP Function
This function returns the first letter in upper case of string.
Output
------------
Sushil Kumar
Syntax: TO_DATE(string/char[,format])
For example: 1. SQL> select TO_DATE('031092','MMDDYY') as “Date” from
dual;
Output:
Date
---------
10-MAR-92
2. SQL> select TO_DATE('1/1/02','mm/dd/yy') "Date" from dual;
Output:
Date
---------
01-JAN-02
AND: This operator gives output if both first condition and the second condition are true.
For example:
15
Let a table test with following details:
ID NAME
---------- ---------------
1 alka
2 saini
ID NAME
---------- ---------------
1 alka
no rows selected
For example:
ID NAME
---------- ---------------
1 alka
ID NAME
---------- ---------------
1 alka
For example:
ID NAME
---------- ---------------
2 saini
16
ID NAME
---------- ---------------
1 alka
Union Clause: This clause is used to display the combined or merged data of two tables. If
there is any duplicate row in both table, that will display only once. The user can combine the
output by putting together multiple queries with the help of union clause.
17
Above two tables shows the records of students of two different subjects. As one student can
read more than one subject, so some records in two tables can common. For example if the
user want to select all the students from both tables, then use union clause as follows:
SQL> SELECT Roll_no as ID, Name from Table1 Union Select Id_no as ID, Name from
Table2;
The output will be:
The above result shows the duplicate rows (i.e. S102, S104) displayed only once and all other
rows of Table1 and Table2.
Limitations:
Aggregate functions cannot applied in union
No. of attributes (Columns) in both queries should same.
Datatype of column in each query should same.
It cannot be used in sub queries.
Intersect Clause:
This clause is also used to combine more than one query like union. But a major difference is
that it will display only that records which are common to both the tables. The intersect
clause output the common rows of both the table.
18
Considering further the above tables i.e. table1 and Table2. If the user wants to select all the
records of students which read both the subjects, then the intersect clause will as follows:
SQL>SELECT Roll_no ID, Name from Table1 INTERSECT Select Id_no ID, Name from
Table2;
The output will be:
19
The above two statements will not produce the same result.
Statement 1 displays all record of Table1 which are not in Table2.
And statement 2 behaves vice-versa, as it displays all the records of Table2 which are not in
Table1.
13.10 Joins
As the name suggests join is used for joining more than one table. Sometimes the user
requires using multiple tables as single entity, which is implemented by join operation. Join
enable the user to manipulate many tables as a single entity using a single SQL statement.
Join operation work on columns or attributes. The user can join tables on columns which
have the same data type and data width.
Some major join operations are:
a) Equi Join / Inner join
b) Self Join
c) Outer Join
a) Equi join: This works on different tables. It combines many tables as single entity.
The user can join two or more tables on columns that have same specifications in all
the tables. Equi join is also called inner join.
For example: Consider the following two tables which give the information related
to a library:
20
Now suppose the user want to display book issue information like Book_No, Title of Book,
and Name of the member to which the book is issued in the ascending order. The query will
as follows:
SQL>SELECT Book_No, Title_of_Book, Name from Book_issue, Member_info
WHERE Book_issue.Member_no = Member_info.Member_no
ORDER BY Member_no;
Note: We are using Table name and Column name separated by period(.) in where clause
because both the tables have same column name.
The output of above query will:
Self Join:
Self-join simply is a join which is used to join a table to itself. The SQL self-join can be done
by using aliases, which can be used to treat one table like a different table. SQL self-join can
be any form of join such as SQL inner join or SQL outer join etc. User can apply any join to
the SQL self-join.
Example: Suppose the user want to select the name of the employees along with their
managers from the following table Table 1.
E102 Jannat -
E104 Pakhi -
21
The query will as follows:
SQL>SELECT X.Name, Y.Name Manager FROM Table1 X, Table1 Y where
X.Manager_no=Y.Emp_no;
In the above query X and Y are the aliases of Table1 , by using this we can use the same
table by two name X and Y. The output will be:
Name Manager
Deepanshu Sakshi
Sakshi Sanjay
Sanjay Jannat
Natural Join:
A natural join statement is used to compare the common columns of two tables with each
other. The user should check whether common columns exist in both tables before doing a
natural join.
Natural joins may cause problems if columns are added or renamed. Also, no more than two
tables can be joined using this method. So, it is best to avoid natural joins as far as possible.
Consider the same example of equi join as this is the same as an equi join on
(Book_issue.Member_no = Member_info.Mamber_no).
Outer Join
An outer join is similar to the equi join, but it will also return non matched rows from the
table. Outer join is of three types:
a) Left Outer Join
b) Right Outer Join
c) Full Outer Join
22
The LEFT JOIN keyword returns all rows from the left table (table_name1), even if
there are no matches in the right table (table_name2).
Syntax:
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Now we want to list all the customers and their orders - if any, from the tables above.
23
The LEFT JOIN keyword returns all the rows from the left table (Customer), even if there
are no matches in the right table (Order1).
The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there
are no matches in the left table (table_name1).
Syntax:
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Example : Continuing the above example, consider the same tables Customer and Order.
Now we want to list all the orders with their customers - if any, from the tables above.
24
LastName FirstName OrderNo
Bagri Tanvi 22456
Bagri Tanvi 24562
Sharma Kamya 77895
Sharma Kamya 44678
- - 34764
The RIGHT JOIN keyword returns all the rows from the right table (Order), even if there are
no matches in the left table (Customer).
The FULL OUTER JOIN keyword return rows when there is a match in one of the tables. It
is also called FULL JOIN.
Syntax:
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Example : Continuing the above example, consider the same tables Customer and Order.
Now we want to list all the orders with their customers and customer with their order.
25
- - 34764
The FULL JOIN keyword returns all the rows from the left table (Customer), and all the
rows from the right table (Order). If there are rows in "Customer" that do not have matches in
"Order", or if there are rows in "Order" that do not have matches in "Customer", those rows
will be listed as well.
Syntax:
CREATE VIEW <view name>
AS <SELECT statement>;
For example:
CREATE VIEW s1 AS
( SELECT C_ID,FIRSTNAME,LASTNAME,CITY FROM customer ) ;
26
Selecting data from view
Syntax: Select <columnlist> FROM view_name [WHERE clause];
For example:
SQL>Desc EMP;
RESULT:
Name Null? Type
-------------------------------- ----------------------- -------------------------
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(3)
AGE NUMBER(3)
ESAL NUMBER(10)
SQL>Desc DEPT;
RESULT:
Name Null? Type
--------------------------------- --------------------- ---------------------------
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
3.Display employee name with empno and job type from emp table.
27
SQL> select empno,ename,job from EMP;
Output:
14 rows selected.
4. Display all employee names and their salaries, whose salary lies between
2000/- and 5000/- both inclusive.
SQL> select ename,sal from EMP where sal between 2000 and 5000;
Output:
ENAME SAL
---------- ----------
JONES 2975
BLAKE 2850
CLARK 2450
SCOTT 3000
28
KING 5000
FORD 3000
6 rows selected.
6. Display all employee names and jobs, whose job title include M.
SQL> select ename,job from emp where job like 'M%';
Output:
ENAME JOB
---------- ---------
JONES MANAGER
BLAKE MANAGER
CLARK MANAGER
Output:
JOB
---------
29
CLERK
SALESMAN
PRESIDENT
MANAGER
ANALYST
8. Display all employee names , salary and 10% rise in salary whose job
type is clerk.
SQL> select ename , sal , sal+0.10* sal from emp where job='CLERK';
Output:
Output:
MIN(SAL) MAX(SAL)
---------- ----------
800 5000
10. Find how many job titles are available in employee table.
SQL> select count (distinct job) as NumberOfJob from emp;
Output:
30
NUMBEROFJOB
-----------
5
Output:
ENAME
----------
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
TURNER
ADAMS
JAMES
ENAME
----------
FORD
MILLER
31
13 rows selected.
Output:
JOB SUM(SAL)
--------- ----------
CLERK 4150
SALESMAN 5600
PRESIDENT 5000
MANAGER 8275
ANALYST 6000
SQL> select dname, count (ename) from emp, dept where emp.deptno=dept.deptno group by
dname;
Output:
DNAME COUNT(ENAME)
-------------- ------------
ACCOUNTING 3
RESEARCH 5
SALES 6
32
TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
COMMENT - add comments to the data dictionary
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the GRANT command
DML is Data Manipulation Language statements. Some examples:
SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency
DCL is Data Control Language statements. Some examples:
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like what rollback segment to use
33