Sie sind auf Seite 1von 37

DBMS Package For Class Project

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.

12.1 Data Types in Oracle

o CHAR: Values of this Datatype are final length character strings of


maximum length 255 characters.
o VARCHAR/VARCHAR2: Values of this Datatype of variable length
character strings of maximum length 2000.
o NUMBER: The NUMBER Datatype is used to store numbers (fixed or
floating point). Numbers of virtually any magnitude may be stored up to 30
digits of precision. Number as large as 9.99*10 to the power of 124 i.e. 1
followed by 125 zeros can be stored.
o DATE: The standard format is DD-MM-YY as in 13-DEC-99. To enter
dates other than the standard format, use the appropriate functions. Date
time stores date in the 24-hour format. By default, the time in a date field is
12: 00: 00 am, if no time portion is specified. The default date for a date
field is the first day of the current month.
o LONG: It is used when variable length character strings commit off 65, 535
characters.

12.2 DDL Commands

1. CREATE TABLE
Syntax: CREATE TABLE tablename (Columname datatype(size),
column name datatype(size); Example

For Example:

0
1. Create client_master table where

Column Name Data Type Size

client_no Varchar 2 6

name Varchar 2 20

address Varchar 2 30

city Varchar 2 15

state Varchar 2 15

pincode number 6

balance_due number 10,2

SQL>Create table client_master (client_no varchar2(6), name varchar2(20), address


varchar2(30), city varchar2(15), state varchar2(15), pincode number(6), balance_due
number(10,2));

2. Create product_master table where

Column Name Data Type Size


Product_no Varchar 2 6
Description Varchar 2 20
Profit_percent Number 2, 2
Unit_measure` Varchar 2 10

1
Qty_on_hand Number 8

Sell_price Number 8, 2
Cost_price Number 8, 2

SQL>Create table product_master (Product_no varchar2(6),Description


varchar2(20),Profit_percent number(2,2),Unit_measure varchar2(10),Qty_on_hand
number(8),Sell_price number(8,2),Cost_price number(8,2));

Creating a table from another table

Syntax:

CREATE TABLE tablename [(columnname, columnname)] AS SELECT columnname, columnname from

tablename;

For Example:

CREATE TABLE s1 AS SELECT * from client_master;

Displaying Description of Table


Syntax:
desc tablename;
For example:

2
2. ALTER TABLE
Syntax:
ALTER TABLE existing_table_name MODIFY (columnname
newdatatype(size));

For Example:

SQL>ALTER TABLE Product_master MODIFY (Description varchar2(25));

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:

SQL>ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);

Similarly, if we want to drop constraint then

SQL>ALTER TABLE EMP DROP CONSTRAINT Pkey1;

3. DROP TABLE
This command deletes table structure and cannot be recovered.

Syntax: DROP TABLE tablename;

For Example:

SQL> DROP TABLE EMP;

4. TRUNCATE TABLE

Syntax: TRUNCATE TABLE tablename;

12.3 DML Commands

1. INSERT
This command is used for inserting data into table.
Syntax: INSERT INTO tablename VALUES (value1,value2, …….);

 Single-row insertion at a time

3
SQL>Insert into Client_master Values ('CN2001', 'Deepak Kumar', 'A-5, Patel Nagar',
'Rohtak', 'Haryana',124001,50000);

SQL>Insert into Client_master Values ('CN2002', 'Naresh Kumar', '618, Sec- 15', 'Gurgaon',
'Haryana',122001,25000);

 Inserting one row, many columns at a time

INSERT INTO tablename (c1,c2, …..) VALUES (value1,value2, …..);

SQL>Insert into Client_master (Client_no, name, address) Values ('CN2003', 'Alka


Saini',’Hansi, Hisar’);

SQL>Insert into Client_master (Client_no, name, address) Values ('CN2004', 'Divyam


Saini',’Gurgaon’);

 Inserting data into table from another table.

Syntax:

INSERT INTO tablename (c1,c2, .... ) SELECT columnname, columnname, .... FROM tablename;

For Example: INSERT INTO NEW_SUPPLIER (name, address)

SELECT name, address FROM S1;

Other Examples:

SQL>Insert into test values (‘ABC’,’05-may-80’);

1 row created

SQL>Insert into test1 values(‘Hema’,’25-sept-91’,’f’,’c++’,’25000’);

1 row created

SQL> Insert into s1 values


('&client_no','&name','&address','&city’,’&state’,&pincode,&balance_due);

2. UPDATE
Syntax: UPDATE tablename SET columnname =value [WHERE condition];

For Examples:

4
1. SQL>UPDATE S1 SET CITY = ‘KANPUR’ WHERE client_no=‘CN2003’;

2. SQL>UPDATE S1 SET balance_due = 2 * balance_due;

3. DELETE

Syntax: DELETE FROM tablename WHERE condition;

For Examples:

1. DELETE FROM S1 WHERE client_no=‘CN2003’;

2. DELETE FROM S1;

12.4 DCL Commands

1. COMMIT Command
The COMMIT command executes a SQL COMMIT command and save
changes for permanent use.

Syntax:
COMMIT;

SQL>commit;

Commit complete.

2. ROLLBACK Command

5
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

This command is used for creating a save point.

Syntax:

SAVEPOINT text_identifier;

Example:
a) UPDATE emp
SET salary = 95000
WHERE emp_id=101;

SAVEPOINT t1;

UPDATE emp
SET salary = 100000;

SAVEPOINT t2;

SELECT SUM(salary) FROM emp;

ROLLBACK TO SAVEPOINT t1;

COMMIT;

b) SQL>SAVEPOINT t3;

SQL>delete test;

2 rows deleted.

SQL> Rollback to savepoint t3;

Rollback complete.

12.5 ORDER BY, GROUP BY, HAVING clause and DISTINCT keyword

6
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:

SQL> select * from test order by name desc;

Output:

ID NAME

---------- ---------------

2 saini

1 alka

SQL> select * from test order by name asc;

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.

For example: Suppose a table s2 with following details:

SQL> select * from s2;

ID NAME
---------- ---------------
1 alka
2 saini
3 alka
4 alka

7
4 alka

Use of GROUP BY:

SQL> select name, sum(id) from s2 group by name;


Output:
NAME SUM(ID)
--------------- ----------
alka 12
saini 2

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 12

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.

Syntax: Select DISTINCT column_name FROM tablename;

For example:

SQL> select DISTINCT name from emp;

12. 6 Data Constraints

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));

Add constraint if table already exist:


ALTER TABLE tablename ADD PRIMARY KEY (Column_name);

DROP primary key constraint:


ALTER TABLE tablename DROP PRIMARY KEY;

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:

Column level constraint:

SQL>Create table Marks (RollNo number(6) REFERENCES STUDENT, Subject1


varchar2(15), Subject2 varchar2(15), Subject3 varchar2(15));

Table level constraint:

SQL>Create table Marks1 (RollNo number(6), Subject1 varchar2(15), Subject2


varchar2(15), Subject3 varchar2(15), FOREIGN KEY (RollNo) REFERENCES
STUDENT);

Add constraint if table already exist:

ALTER TABLE tablename ADD CONSTRAINT fk FOREIGN KEY (Column_name)


REFERENCES primarykeytablename );
e.g. SQL> ALTER TABLE Marks1 ADD CONSTRAINT fk FOREIGN KEY (RollNo)
REFERENCES STUDENT;

DROP foreign key constraint:

9
ALTER TABLE tablename DROP CONSTRAINT foreignkeyname ;
e.g. SQL> ALTER TABLE Marks1 DROP CONSTRAINT fk;

Unique Key: A Unique key constraints is also a unique identifier for


a row with in a database table. Primary key values cannot be null
but Unique constraint allows only one null value for the specified
field.

For Example:

Column level constraint:


SQL>Create table Test1 (ID varchar2(6) CONSTRAINT un UNIQUE, name varchar2(15),
address varchar2(30), city varchar2(15));

Table level constraint:


SQL>Create table Test2 (ID varchar2(6), name varchar2(15), address varchar2(30), city
varchar2(15), CONSTRAINT unk UNIQUE(ID) );

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));

CHECK Constraint: A check constraint is used to specify a condition on


each row in a table. A check constraint cannot be defined on a VIEW and
cannot include a SUBQUERY.

For Example:

Column level constraint:

SQL>Create table Test5 (ID varchar2(6), name varchar2(15) CONSTRAINT cn CHECK


(name like ‘S%’), address varchar2(30), city varchar2(15));

Table level constraint:

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));

12.7 SQL Functions

Some most usefull function of SQL are:

1. AVG() Function
The AVG() function returns the average value of a numeric filed.

Syntax: AVG(filedname)
Example:

1. SELECT AVG(OrderPrice) FROM Orders;


2. SELECT ename FROM emp WHERE sal>(SELECT AVG(sal) FROM emp);

2. COUNT() Function
This function returns the number of values and NULL values are not counted by this
function.

Syntax: COUNT(filedname)

Example:

SELECT COUNT(sal) FROM emp;

3. MAX() Function
This function returns the largest value of the selected column.

11
Syntax: MAX(filedname)

Example:

SELECT MAX(sal) FROM emp;

4. MIN() Function
This function returns the smallest value of the selected column.

Syntax: MIN(filedname)

Example:

SELECT MIN(sal) FROM emp;

5. SUM() Function
This function returns the total sum of a column but column must be numeric.

Syntax: SUM(filedname)

Example:

SELECT SUM(sal) FROM emp;

6. UPPER() Function
This function converts the value of a field to uppercase.

Syntax: UPPER (filedname)

Example:

 SELECT UPPER (name) FROM emp;

 SELECT UPPER (‘dbms’) FROM dual;

7. LOWER () Function
This function converts the value of a field to lowercase.

12
Syntax: LOWER (filedname)

Example:

 SELECT LOWER (name) FROM emp;

 SELECT LOWER (‘DBMS’) FROM dual;

8. LENGTH() Function
This function returns the length of the value in a text field.

Syntax: LENGTH (filedname)

Example:

I. SELECT LENGTH (name) FROM emp;


II. SQL> SELECT LENGTH('DBMS') from dual;
Output:

LENGTH('DBMS')
--------------
4

9. SQRT() Function
This function returns the square root of the specified field or numeric expression.

Syntax: SQRT (filedname)

Example:

I. SELECT SQRT (sal) FROM emp;

II. SELECT SQRT (16) FROM emp;

III. SELECT SQRT (2 + 14) FROM dual;

10. ABS() Function


This function returns the absolute value of number.

13
Syntax: ABS (number)

Example:

SQL>SELECT ABS (-19) FROM dual;


Output:
ABS(-19)
----------
19

11. ROUND() Function


This function returns the rounded value of specified value or filed.

Syntax: ROUND (number [,n])

Returns number rounded to n places right of the decimal point.

Example:

SELECT ROUND (19.79,1) FROM dual;

Output:

ROUND(19.79,1)

--------------

19.8

12. POWER() Function

Syntax: POWER(number ,n)

This function returns the number raised to nth power, both the value must be numeric.

Example:

SELECT POWER(5,2) FROM dual;

Output:
POWER(5,2)
----------
25

14
13. INITCAP Function
This function returns the first letter in upper case of string.

Syntax: INITCAP(string) or INITCAP(fieldname)


For example: SQL>select INITCAP(‘sushil kumar’) “Output” from dual;
Output:

Output

------------

Sushil Kumar

14. TO_DATE Function


This function coverts a character or string field to a date field.

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

12.8 Logical Operators

Logical operators used in SQL are:


 AND
 OR
 NOT

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:

SQL> select * from test;

ID NAME
---------- ---------------
1 alka
2 saini

SQL> select * from test where id=1 and name='alka';

ID NAME
---------- ---------------
1 alka

SQL> select * from test where id=1 and name='al';

no rows selected

OR: This operator gives output if any one condition is true.

For example:

SQL> select * from test where id=1 or name='al';

ID NAME
---------- ---------------
1 alka

SQL> select * from test where id=5 or name='alka';

ID NAME
---------- ---------------
1 alka

NOT: This operator is used for negation.

For example:

SQL> select * from test where id not in 1;

ID NAME
---------- ---------------
2 saini

SQL> select * from test where id not between 2 and 4;

16
ID NAME
---------- ---------------
1 alka

12. 9 Union, Intersection and Minus clause

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.

The output of union clause is


Records that are only in Table 1+Records those are only in Table 2+ A single set of records
which are common in Table1 and Table 2.
For e.g. consider the following tables:

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:

Union of Table1 and Table2

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.

The output of intersect clause is


A single set of records which are common in Table1 and Table 2.

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:

Intersection of Table1 and Table2


The above result shows only the common rows (i.e. S102, S104) are displayed only once.
Minus Clause:
This clause is used to select the rows from only one table which are unique in that table. That
means which are not common as shown in following pictorial representation.

Statement 1: SQL> select * from table1 minus select * from table2;


&
Statement 2: SQL> select * from table2 minus select * from table1;
Outputs:

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.

12.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.

Here is common syntax of SQL self-join:

SELECT column_list FROM table_A AS A


INNER JOIN table_A AS B
ON A.column_name1 = B.column_name2, ...
WHERE row_conditions

Example: Suppose the user want to select the name of the employees along with their
managers from the following table Table 1.

Emp_No Name Manager_No

E101 Deepanshu E103

E102 Jannat -

E103 Sakshi E105

E104 Pakhi -

E105 Sanjay E102

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

a) Left 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

Example : Consider the following two tables :


The “Customer “ table is :

C_Id FirstName LastName City


1 Punit Taneja Sonipat
2 Tanvi Bagri Sonipat
3 Kamya Sharma Yamunanagar

The "Order1" table:

O_Id OrderNo C_Id


1 77895 3
2 44678 3
3 22456 2
4 24562 2
5 34764 15

Now we want to list all the customers and their orders - if any, from the tables above.

We use the following SELECT statement:

SQL>SELECT Customer.LastName, Customer.FirstName, Order1.OrderNo


FROM Customer
LEFT JOIN Order1
ON Customer.C_Id=Order1.C_Id
ORDER BY Customer.LastName;

The result-set will look like this:

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).

b) Right Outer Join

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

In some databases RIGHT OUTER JOIN is called RIGHT JOIN.

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.

We use the following SELECT statement:

SQL>SELECT Customer.LastName, Customer.FirstName, Order1.OrderNo


FROM Customer
RIGHT JOIN Order1
ON Customer.C_Id=Order1.C_Id
ORDER BY Customer.LastName;

The result-set will look like this:

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).

c) Full Outer Join

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.

We use the following SELECT statement:

SQL>SELECT Customer.LastName, Customer.FirstName, Order1.OrderNo


FROM Customer
FULL JOIN Order1
ON Customer.C_Id=Order1.C_Id
ORDER BY Customer.LastName;

The result-set will look like this:

LastName FirstName OrderNo


Bagri Tanvi 22456
Bagri Tanvi 24562
Sharma Kamya 77895
Sharma Kamya 44678
Taneja Punit -

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.

12.11 VIEW: A view is a virtual table that does not physically


exist. It is derived from another existing table in the database,
which is known as base tables. View avoids duplication of data and
provides data security.

Syntax:
CREATE VIEW <view name>
AS <SELECT statement>;

For example:
CREATE VIEW s1 AS
( SELECT C_ID,FIRSTNAME,LASTNAME,CITY FROM customer ) ;

To delete a view use DROP VIEW command as follow:


DROP VIEW s1;
Updating a VIEW
You can update a VIEW without dropping it by using the
following syntax:
CREATE OR REPLACE VIEW view_name AS
<SELECT statement>;

26
Selecting data from view
Syntax: Select <columnlist> FROM view_name [WHERE clause];
For example:

Select C_ID,FIRSTNAME,LASTNAME,CITY FROM s1;

12.12 Some Simple Queries

1. Get the description of EMP table.

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)

2. Get the description DEPT table.

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:

EMPNO ENAME JOB


---------- ---------- ---------
7369 SMITH CLERK
7499 ALLEN SALESMAN
7521 WARD SALESMAN
7566 JONES MANAGER
7654 MARTIN SALESMAN
7698 BLAKE MANAGER
7782 CLARK MANAGER
7788 SCOTT ANALYST
7839 KING PRESIDENT
7844 TURNER SALESMAN
7876 ADAMS CLERK

EMPNO ENAME JOB


---------- ---------- ---------
7900 JAMES CLERK
7902 FORD ANALYST
7934 MILLER CLERK

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.

5. Display all employees name which starts with either A or R.


SQL> select ename from emp where ename like 'A%' or ename like 'R%';
Output:
ENAME
----------
ALLEN
ADAMS

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

7. Display all jobs available in emp table.

SQL> select distinct job from emp;

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:

ENAME SAL SAL+0.10*SAL

---------- ---------- ------------

SMITH 800 880

ADAMS 1100 1210

JAMES 950 1045

MILLER 1300 1430

9. Display minimum and maximum salaries of employee.


SQL> select min(sal),max(sal) from emp;

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

11. Find ename whose manager is not NULL.


SQL>select ename from emp where mgr is not null;

Output:

ENAME

----------

SMITH

ALLEN

WARD

JONES

MARTIN

BLAKE

CLARK

SCOTT

TURNER

ADAMS

JAMES

ENAME

----------

FORD

MILLER

31
13 rows selected.

12. Display total salary spent for each job category.


SQL> select job,sum (sal) from emp group by job;

Output:
JOB SUM(SAL)
--------- ----------
CLERK 4150
SALESMAN 5600
PRESIDENT 5000
MANAGER 8275
ANALYST 6000

13. Display number of employees working in each department and their


department name.

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

Review Exercise

1. Create a table Product for the following details:

Column Name Data Type Size Attributes

SNo number 6 Primary key

ProductName Varchar 2 20 Not Null

32
Price number 10,2 Not Null

QTY number 6 Default ‘1’

DOP date

Warranty number 6

2. Insert the following data into the Product table using SQL insert statement:

SNo ProductName Price QTY DOP Warranty


1 Computer 5000 6 13/10/03 2
2 Printer 1500 4 15/01/04 4
3 Scanner 800 2 19/07/02 1
4 Webcam 1200 5 13/10/03 5
5 Plotter 3000 3 12/04/02 3
6 Ups 5000 1 17/02/99 2
7 Speaker 200 15 07/01/04 1

3. Write following SQL statement based on Product table:

(a) Write a query for display the productname in ascending order of the price where quantity is
more than 4.
(b) Write a query for display the number of computers,scanners and webcams.
(c ) Write a query for change the price to 3000 for the productname webcam.
(d) Write a query for inserting a new record in to the table with the following data
8,”Mouse”,300,6, 13/10/03,2
(e) Write a query for display details of those products which purchased on “13/10/03”.

4. Create a table BookDetails for the following details:

Column Name Data Type Size Attributes

SNo number 6 Primary key

33
Title Varchar 2 20 Not Null

AuthorName Varchar 2 20 Not Null

Publisher Varchar 2 20

Qty number 6 Default ‘1’

Price number 10,2

5. Insert the following data into the BookDetails table using SQL insert statement:

SNo Title AuthorName Publisher Qty Price


1 Database Management Sushil Kumar Unique 10 145
System
2 C++ Balaguruswamy Mc Graw 5 200
3 Data structures Horowitz Mc Graw 4 250
4 Visual Basic Gurewich PHI 2 400
5 Networks Freed BPB 1 600
6 Oracle 8i Palmer Galgotia 3 700
7 Java script Schildt Mc Graw 5 300
8 Oracle Developer Ivan Bayross BPB 2 200

6. Write following SQL statement based on BookDetails table:

(a) Write a query for display the details of all the books published by Mc Graw.
(b) Write a query for display total cost of purchasing the books whose author is “Sushil Kumar”.
(Total Cost= Qty * Price)
(c ) Write a query for display a list of books with price more than 400.
(d) Write a query display the number of books published by BPB.
(e) Write a query for display the details of the books for which total cost is maximum.

34
7. Create a table Employee for the following details:

Column Name Data Type Size Attributes

ENo Varchar 2 6 Primary key

EName Varchar 2 20 Not Null

Job Varchar 2 20 Not Null

Mgr Varchar 2 20

Salary number 6

DOJ date

DNo number 6

8. Insert the following data into the Employee table using SQL insert statement:

ENo EName Job Mgr Salary DOJ DNo


E1000 Allen Director 7000 14/02/95 12
E1695 Smith Manager E1000 5000 10/02/97 20
E1566 Martin Manager E1000 5200 23/07/96 10
E1350 Jones Clerk E1695 1250 17/02/98 15
E1352 Ford Analyst E1566 4000 12/07/99 20
E1353 Adams Clerk E1695 1200 11/11/99 15
E1356 James Salesman E1566 800 12/02/98 20

9. Write following SQL statement based on Employee table:

(a) Write a query for display all employees details whose names begins with the alphabet ‘A’.
(b) Write a query for minimum and maximum salary for each job type.
© Write a query for find out the number of employees having job as Manager.
(d) Write a query for calculate the average salary for each department.
(e) Write a query for display the salary with 12% increment.

35
10. Create a table Student for the following fields:
RollNo, Name, DOB, Subject1, Subject2, Subject3.

a. Write a SQL statement for adding a new column Grade.


b. Insert 5 rows in Student table with SQL insert statement.
c. Write a SQL statement for display results with total marks(Subject1+Subject2+Subject3) and
percentage.
d. Write a SQL statement for display student name with ascending order of total marks.
e. Write a SQL statement for find out how many students score is > 50%.

36

Das könnte Ihnen auch gefallen