Chapter 4 Dbms

38
SQL 4. SQL 4.1 Tools Of Oracle Structured Query Language(SQL): It has 9 commands which are common to all DBMS CREATE, DROP, ALTER for Tables INSERT,UPDATE,DELETE for Records GRANT, REVOKE for Permission SELECT for Query SQL*PLUS: It is extension to SQL. Procedural Language SQL (PL*SQL): It is programming language native to Oracle. It supports OOPS. It’s a forth generation language (4GL). Forms: It is used for creating data entry screens. It is graphical user interface, front end, client side, form’s tool. It is part of Oracle’s Internet Development Suite Reports: A report writer in Oracle. Menus: It is part of Oracle’s Internet Development Suite Graphics: It is part of Oracle’s Internet Development Suite IDS: It includes the above four tools i.e. Forms, Reports, Menus, and Graphics. It is part of Oracle’s Internet Development Suite EXP: This is used to take Oracle database backups IMO: This is used to restore backups Oracle terminal: Used for Keyboard mapping SQL *Loader: Converts files from other RDBMS to Oracle SQL *DBA,SVRMGR,OEM: Database Administration Oracle Case: Cad,DFD,ERP,Diagrams Designer 2000: It includes Oracle CASE tools plus an IDS Oracle Power Objects: support for VB Oracle Objects for QLE: C++ and VB connectivity Oracle Manufacturing: software for manufacturing processes Oracle Financials: Accounting software (ERP) 1

description

Learn SQL Effectively with easy way.

Transcript of Chapter 4 Dbms

Page 1: Chapter 4 Dbms

SQL

4. SQL4.1 Tools Of Oracle

Structured Query Language(SQL): It has 9 commands which are common to all DBMS CREATE, DROP, ALTER for Tables INSERT,UPDATE,DELETE for Records GRANT, REVOKE for Permission SELECT for Query

SQL*PLUS: It is extension to SQL. Procedural Language SQL (PL*SQL): It is programming language native to

Oracle. It supports OOPS. It’s a forth generation language (4GL). Forms: It is used for creating data entry screens. It is graphical user interface,

front end, client side, form’s tool. It is part of Oracle’s Internet Development Suite

Reports: A report writer in Oracle. Menus: It is part of Oracle’s Internet Development Suite Graphics: It is part of Oracle’s Internet Development Suite IDS: It includes the above four tools i.e. Forms, Reports, Menus, and Graphics. It

is part of Oracle’s Internet Development Suite EXP: This is used to take Oracle database backups IMO: This is used to restore backups Oracle terminal: Used for Keyboard mapping SQL *Loader: Converts files from other RDBMS to Oracle SQL *DBA,SVRMGR,OEM: Database Administration Oracle Case: Cad,DFD,ERP,Diagrams Designer 2000: It includes Oracle CASE tools plus an IDS Oracle Power Objects: support for VB Oracle Objects for QLE: C++ and VB connectivity Oracle Manufacturing: software for manufacturing processes Oracle Financials: Accounting software (ERP) Oracle HRMS: HRD Software Oracle Application: It includes Oracle manufacturing, Oracle financials &

Oracle HRMS Oracle CRM: Software used in call center, E sales, E marketing Oracle Web Browser: For browsing an Oracle database Discover 2000: It includes Oracle Web Browser plus an IDS Personal Oracle: Single user version of the Oracle database engine

1

Page 2: Chapter 4 Dbms

SQL

4.2 Data Types

TYPES DATATYPE CHAR(size) VARCHAR(size)/VARCHAR2(size) DATE NUMBER(P,S) LONG RAW/LONG RAW

CHAR(SIZE)

This data type is used to store character strings values of fixed length. The size represents length of character should be stored This data can store maximum 255 characters. Example: Name CHAR(60)

VARCHAR(size)/VARCHAR2(size)

This data type used store variable length alphanumeric data. The maximum size of this data type is 4000 characters.

DATE This data type is used to store date and time. The standard format is DD-MON-YY for example 21-JUN-09. Date time stores time in the 24-hours format. Range of this data type is January 1, 4712 B.C. to December 31, 4712 A.D.

NUMBER(P,S) The NUMBER data type is used store numbers (both Integer and floating

point numbers). We can store number up to 38 characters long. The precision (P), determines the maximum length of number, and scale (s),

determines the point sign (.) right from a number(P).

LONG This data type is used to store variable length character strings up to 2 GB. LONG data can be used to store binary data in ASCII format.

RAW/LONG RAW The RAW/LONG RAW data type are used to store binary data, such as

digitized picture or image RAW data type can have a maximum length of 255 bytes. LONG RAW data type can contain up to 2 GB.

2

Page 3: Chapter 4 Dbms

SQL

4.3 Database Language DDL(Data-Definition Language)

“We specify a database schema by a set of definition expressed by a special language called a data-definition language(DDL)”

DDL commands generally used for design or define database CREATE, ALTER, TRUNCATE, DROP TABLE

CREATE Create command used to create a table in database.

Syntax:Create table <table name>

( <columnname1> <datatype> (<size>), <columnname2> <datatype> (<size>));

Example:create table client_master ( client_no varchar2(6), name varchar2(20), city varchar2(15), pincode number(8), state varchar2(15) );

ALTER Alter command used to modify structures of a table. Alter command can be used to add ,modify, or drop columns in a table

Syntax:Adding New Columns Alter table TableName

Add (NewColumnName Datatype(size), NewColumnName Datatype(size)….);

Modifying Existing Columns Alter table TableName

Modify (ColumnName NewDatatype(NewSize));

Dropping(deleting) Existing Columns Alter table TableName

Drop column columname;

3

Page 4: Chapter 4 Dbms

SQL

Example:1). alter table client_master add(telephone_no number(10));2) alter table product_master modify(SELL_PRICE number(10,2));3) alter table emp drop column dept;

TRUNCATE TABLE TRUNCATE TABLE used to delete all data from a table Logically, this is equivalent to DELETE statement that deletes all rows TRUNCATE command is faster than DELETE command The number of deleted rows are not returned

Syntax:TRUNCATE TABLE <TableName>

Example:TRUNCATE TABLE client_master;

DROP TABLE DROP TABLE command is used to delete or destroy table from a database

Syntax:DROP TABLE <TableName>

Example:DROP TABLE client_master;

DML (Data-Manipulation language)

DML commands are generally used for manipulating data stored in tables.So dml commands are work on data stored in tables rather than table definitionIt include following commands

INSERT,SELECT,UPDATE,DELETE

INSERT Used to insert data into a table or create a new row in table:

Syntax:Insert table <table name> (<columnname1>,<columnname12>) values (<expression1>,<expression2>);

Example:Insert table client_master (client_no,name)

Values (‘C00001’,’RAHUL’);

4

Page 5: Chapter 4 Dbms

SQL

SELECT The SELECT command is used to retrieve selected rows from one or more

tables

Syntax:1). SELECT * FROM <TableName>;2). SELECT <ColumnName1>,<ColumnName1>

From <TableName>;3). SELECT * FROM <TableName> WHERE <Condition>;4). Etc

Example:1). SELECT * FROM client_master;2). SELECT name, city FROM client_master;3). SELECT * FROM client_master

Where city=’Bombay’;

UPDATE The UPDATE command is used to change or modify data of a table Update command used to update

Selected rows from table All the rows from table

Syntax:Update <table name>

Set <columnname1> = <expression1>, <columnname1> = <expression2>;

Example:Update client_master

Set city=’Bombay’;

DELETE Delete command used to delete data or rows from a table delete command used to delete

Selected rows from table All the rows from table

Syntax:1) Delete from <table name>; 2) Delete from <table name> Where <Condition>;

Example:1) Delete from client_master; 2) Delete from client_master Where client_no=’C00001’;

4.4 Operators

5

Page 6: Chapter 4 Dbms

SQL

Arithmetic Operators Oracle allows arithmetic operators to used while viewing records from table or

while performing data manipulation operations such as Insert, Update and Delete. These are:

+ Addition * Multiplication** Exponentiation () Enclosed operation- Subtraction / Division

Example: Select product_no, description, sell_price * 0.05 from product_master;

Logical Operators The AND Operator The OR Operator Combining the AND and OR Operator The NOT Operator

The AND Operator The AND Operator allows creating an SQL statement based on two or more

conditions being met. It can be used in any valid SQL statement such as select, insert, or delete. Example: Select product_no, description, sell_price * 0.05 from

product_master where sell_price between 500 and 1100;

The OR Operator The OR condition allows creating an SQL statement where records are

returned when any one of the conditions are met It can be used in any valid SQL statement such as select, insert, or delete. Example: select client_no, name, city, pincode from client_master

Where pincode=4000054 or pincode=4000057;

Combining the AND and OR Operator The AND and OR conditions can be combined in a single SQL statement It can be used in any valid SQL statement such as select, insert, or delete.

The NOT Operator The Oracle engine will process all rows in a table and display only those

records that do not satisfy the condition specified Example: select * from client_master where not ( city=’Bombay’, or

city=’Delhi’ );

6

Page 7: Chapter 4 Dbms

SQL

Comparison Operators Comparison operators are used in condition to compare one expression with other.

The comparison operators are =, <, >, >=, <=, !=, between, like, is null and in operators

Between operator is used to check between two values or specific range Example:

SQL>select * from salesman_master where salary between 5000 and 8000; The above select statement will display only those rows where salary of

salesman is between 5000 and 8000.

In operator: The IN operator can be used to select rows that match one of the values in a

list SQL> select * from client_master where client_no in(C00001, C00003); The above query will retrieve only those rows where client_no is either in

C00001 or C00003

Like operator: Like operator is used to search character pattern,. The like operator is used with special character % and _(underscore) SQL> select * from client_master where city like ‘ b% ’; The above select statement will display only those rows where city is start

with ‘B’ followed by any number of any characters. % sign is used to refer number of character ( it similar to * asterisk wildcard in

DOS). While _(underscore) is used to refer single character. SQL> select * from client_master where name like ‘_ahul’;

4.5 SQL functions Single row functions

Date function

ADD_MONTHS() It returns the date after adding the number of months in specific date. Syntax: ADD_MONTHS(date,number) Example: select ADD_MONTHS (’04-jun-2009’,2) from dual; Output: 04-AUG-2009

MONTHS_BETWEEN It returns the number of months between the specified dates. Syntax: MONTHS_BETWEEN(date1,date2) Example: select MONTHS_BETWEEN (’02-FEB-09’,’02-JAN-09’) from

dual; Output: 1

7

Page 8: Chapter 4 Dbms

SQL

Round() This function round a date in specified format Syntax: ROUND(date,format) Example: select ROUND(sysdate,’year’) from dual; Output:-1-jan-2013

NEXT_DAY It returns the date of the first weekday after specified date. Syntax: NEXT_DAY(date,’char’) Example: select NEXT_DAY(‘04-FEB-09’,’FRIDAY’) from dual; Output: 06-FEB-09

TRUNC() This function trunc a date in specified format Syntax: trunc(date,format) Example: select trunc(sysdate,’year’) from dual; Output:-01-jan-2012

GREATEST() It displays the latest date from a list of dates Syntax: GREATEST (date1, date2, date3 …) Example: select GRETEST(’02-FEB-09’, ’02-JAN-09’) from dual; Output: 02-JAN-09

NEW_TIME() It display the date in the required time zone Syntax: : NEW_TIME (date,currenttimezone,newtimezone) Example: select NEW_TIME(sysdate,'EST','HST') from dual; Output: 22-JUL-09

Numeric function

ABS() It returns the absolute value. Syntax: ABS(n) Example: select ABS(-15) from dual; Output: 15

CEIL() It returns the smallest integer that is greater than or equal to a specific

value Syntax: CEIL(n) Example: select CEIL(1.3) from dual; Output:2 Example: select CEIL(2) from dual; Output:2

8

Page 9: Chapter 4 Dbms

SQL

Example: select CEIL(-2.3) from dual; Output:2

COS() It returns the cosine of a given value. Syntax: COS Example: select COS(45) from dual; Output: 1

COSH() It returns hyperbolic cosine of a given value. Syntax: COSH Example: select COSH(45) from dual; Output: 1.7467E+19

EXP() It returns e raised to the nth power, where e=2.71828183. Syntax: EXP(n) Example: select EXP(5) “Exponent” from dual; Output: Exponent

148.413159 FLOOR()

It returns the greatest integer that is less than or equal to a specific value. Syntax: FLOOR(n) Example: select FLOOR(1.3) from dual; Output: 1 Example: select FLOOR(2) from dual; Output: 2 Example: select FLOOR(-2.3) from dual; Output: -3

POWER() It returns the value raised to a given positive exponent. Syntax: POWER(value, exponent) Example: select POWER(3,2) from dual; Output: 9 Example: select POWER(64,0.5) from dual; Output: 8

MOD() It divides a value by a divisor and returns the remainder. Syntax: MOD(value, divisor) Example: select MOD(100,10) from dual; Output: 0 Example: select MOD(10,3) from dual; Output: 1

9

Page 10: Chapter 4 Dbms

SQL

Example: select MOD(-30.23,7) from dual; Output: -2.23

ROUND() It rounds a number to given number of digits of precision Syntax: ROUND(value, precision) Example: select ROUND(66.666,2) from dual; Output: 66.67

TRUNC() It truncates digits of precision from a number Syntax: TRUNC(value, precision) Example: select ROUND(66.666,2) from dual; Output: 66.66

SORT() It returns the square root given number Syntax: SQRT(n) Example: select SQRT(64) from dual; Output: 8

Character function

INITCAP() Returns a string with the first letter of each word in UPPER CASE Syntax: INITCAP(char) Example: select INITCAP('rahul kumar') from dual; Output: Rahul Kumar

LOWER() It takes any string or column and converts it into lowercase Syntax: LOWER(string) Example: select LOWER(‘RAHUL’) from dual; Output: rahul

UPPER() It takes any string or column and converts it into upper case Syntax: UPPER(string) Example: select UPPER(‘rahul’) from dual; Output: RAHUL

LTRIM() It removes character from the left of char with initial characters removed

up to the first character not in set Syntax: LTRIM(char, set) Example: select LTRIM(‘RAHUL’,’R’) from dual;

10

Page 11: Chapter 4 Dbms

SQL

Output: AHUL

RTRIM() It returns char with final character removed after the last character not in

the set. ’set’ is optional, it defaults to spaces. Syntax: RTRIM(char, set) Example: select RTRIM(‘RAHUL’,’L’) from dual; Output: RAHU

TRANSLATE() Replace a sequence of character in a string with another set of character. Syntax: TRANSLATE(string1,string to replace, replacement string) Example: select TRANSLATE(‘1sct523’,’123’,’7a9’) from dual; Output: 7sct5a9

REPLACE() It replaces a character in a string with zero or more character. Syntax: REPLACE(string1, character to be replaced, characters) Example: select REPLACE(‘Hello’, ’o’, ’rec’ ) from dual; Output: hellrec

SUBSTRING() It returns a substring from a given string It returns a portion of char, beginning at character m exceeding up to n

characters. Syntax: SUBSTR(string) Example: select SUBSTR(‘SECURE’,3,4) from dual; Output: CURE

Conversion function

TO_CHAR() It converts a value of DATE data type to CHAR value. It accept a date as

well as the format in which the date has to appear. The format must be a date format

Syntax: TO_CHAR(date, format) Example: select TO_CHAR(SYSDATE,’DD-MM-YY’) from dual; Output: 22-07-09

TO_DATE() It converts a CHAR filed to a DATE filed. Syntax: TO_DATE (‘char’, format) Example: select TO_DATE(‘26/08/09’,’DD/MM/YY’) from dual; Output: 26-AUG-09

TO_NUMBER()

11

Page 12: Chapter 4 Dbms

SQL

It converts a character value containing a number to a value of NUMBER data type.

Syntax: TO_NUMBER(’char’) Example: select TO_NUMBER(‘100’) from dual; Output: 100

Miscellaneous function

UID It returns an integer that uniquely identifies the session user. Example: select UID from dual; Output: 18

USER It returns the name by which the current user is know to Oracle. Example: select USER from dual; Output: scott

NVL It stands for Null value Substitution. Syntax: NVL(value, substitute) If the value is NULL, this function is equal to substitute. If the value is not NULL, this unction is equal to value. Example

Table name: Shipping

Client WeightJohnson tools 59Inf Software 27Peterson Industries NULL

Select NVL (weight, 43) from shipping;

Client WeightJohnson tools 59Inf Software 27Peterson Industries 43

In the above output, the NVL function replaces the value specified in wherever it encounters a NULL value. Hence, 43 is inserted for client Peterson Industries.

VSIZE

12

Page 13: Chapter 4 Dbms

SQL

It returns the number of bytes in the internal representation of an expression.

Syntax: VSIZE(expression) Example: select VSIZE(‘SCT on the net’) from dual; Output: 14

Group function

AVG() It returns average value of the specified column, ignoring NULL values. Syntax: AVG(Column name) Example: select AVG(sell_price) from product_master; Output: 2012.345

MIN() It returns the minimum value in the specified column. Syntax: MIN(column name) Example: select MIN(sell_price) from product_master; Output: 250

MAX() It returns the maximum value in the specified column. Syntax: MAX(column name) Example: select MAX(sell_price) from product_master; Output: 1500

SUM() It returns the sum of values of the specified column. Syntax: SUM(column name) Example: select SUM(salary) from salesman_master; Output: 65000

COUNT() It returns the number of rows in specified column or the total number of

rows in the table. Syntax: COUNT(column name) Example: select COUNT(salesman_no) from salesman_master; Output: 15 Syntax: COUNT(*) Example: select COUNT(*) from salesman_master; Output: 50

Decode

It is transformation function that does an orderly value-by-value substitution. Syntax: DECODE(string,if1,then1,if2,then2,…..,else)

13

Page 14: Chapter 4 Dbms

SQL

Example: Select supplier_name, DECODE (supplier_id, 10000, ’IBM’, 10001, ’Microsoft’, 10002,’Hewlett Packard’, ’gateway’) result FROM suppliers;

The above decode statement is equivalent to the following IF-THEN-ELSE statement

IF supplier_id = 10000 THENResult: = ‘IBM’;

ELSEIF supplier_id = 10001 THENResult: = ‘Microsoft’;

ELSEIF supplier_id = 10002 THENResult: = ‘Hewlett Packard’;

ELSEResult: = ‘gateway’;

END IF;

The Decode function will compare each supplier_id value, one by one

Group by, Having by and order by clause

GROUP BY Clause GROUP BY clause is another section of the select statement This optional clause tells Oracle to group rows based on distinct values that

exist for specified columns The GROUP BY clause creates a data set, containing several sets of records

grouped together based on a condition

Syntax:Select <column name1>,<column name2>, <column nameN>

AGGREGATE_FUNCTION (<Expression>) From Table Name WHERE <condition> GROUP BY<column name1>,<column name2>,<column nameN>;

Example:SELECT branch_no“branch_no”,COUNT(emp_no)”No Employees”

From emp_master GROUP BY branch_no;

HAVING Clause

14

Page 15: Chapter 4 Dbms

SQL

HAVING Clause can be used in conjunction with the GROUP BY clause HAVING imposed a condition on the GROUP BY clause.

which further filter the group created by the groups by clause Syntax:

Select <column name1>,<column name2>, <column nameN> AGGREGATE_FUNCTION (<Expression>) From Table Name WHERE <condition> GROUP BY<column name1>,<column name2>,<column nameN>; HAVING <condition> Example:

Select product_no,sum (qty_ordered) “total QTY ordered” From sales_order GROUP BY product_no

HAVING product_no=’P00001’ or product_no=’P00004’ HAVING clause is specified row displayed on screen.

ORDER BY Clause ORDER BY is use want the information it return sorted in the order specify. Syntax: Select <column name1>,<column name2>, <column nameN>

From Table Name Where <condition>ORDER BY <column name1>;

Example:Select feature, section, page from NEWSPAPERWhere section=’F’ORDER BY feature;

Set operators UNION, INTERSECT, MINUS

UNION Clause The UNION clause merges or combines the output of two or more queries

into a single set of rows and columns Multiple queries can be put together and their output combined using the

UNION clause.

15

Page 16: Chapter 4 Dbms

SQL

The output of both queries will be displayed as above. Output : Record only in query one + records only in query two + a single set

of records which is common in both queries

Example:

Table Name: client_master

Client_no Name City C00001 Ivan bay Ross BombayC00002 Vandana MadrasC00003 Pramala Bombay

Table Name: salesman_master

Salesman_no Name CityS00001 Kiran Bombay S00002 Manish DelhiS00003 Ravi Bombay

16

Page 17: Chapter 4 Dbms

SQL

Select salesman_no “ID”, name from salesman_masterWhere city=’bombay’

UNIONSelect client_no “ID”, name from client_master

Where city=’bombay’;

OUTPUT:ID Name C00001 Ivan bayrossC00003 PramalaS00001 KiranS00003 Ravi

Restriction on UNION clause : The number of column in all the queries should be same. The data type of columns in each query should be same Unions cannot be used in Sub queries Union cannot be used with aggregate functions

INTERSECT Clause The INTERSECT clause outputs only those rows produced by both queries

intersected. The output of INTERSECT clause will include only those rows that are

retrieved by both the queries.

The output of both queries will be displayed as above The final output of INTERSECT clause will be: Output: A single set of Records which is common in both queries. Example: Retrieve the salesman name in ‘Bombay’ whose efforts have

resulted into at least one sales transaction

17

Page 18: Chapter 4 Dbms

SQL

Table Name: salesman_master

Sman_no name CityS00001 Kiran Bombay S00002 Manish DelhiS00003 Ravi Bombay

Table Name: sales_order

Order_no Order_date Sman_noO19001 12-Apr-08 S00001O19002 25-Dec-08 S00003O19003 19-Oct-08 S00001O19004 02-May-08 S00002

SQL> select sman_no, name from salesman_master where city='bombay' INTERSECT select salesman_master.sman_no , name from salesman_master, sales_order where salesman_master.sman_no=sales_order.sman_no;

Output:Sman_no nameS00001 KiranS00003 Ravi

MINUS Clause The MINUS clause outputs the rows produced by the first query, after

filtering the rows retrieved by the second query.

The output of both queries will be displayed as above The final output of MINUS clause will be:

18

Page 19: Chapter 4 Dbms

SQL

Output: Records only in query one Example: Retrieve all the product number of non-moving items from the

product_master table.

Table Name: sales_order_details

Order_no product_noO19001 P00001O19001 P00004O19001 P00006O19002 P00002O19002 P00005O19003 P00003O19004 P00001O19005 P00006O19005 P00004O19006 P00006

Table Name: product_master

Product_no DescriptionP00001 1.44 floppiesP00002 MonitorsP00003 MouseP00004 1.22 floppiesP00005 KeyboardsP00006 CD driveP00007 HDDP00008 1.44 driveP00009 1.22 drive

Select product_no from product_masterMINUSSelect product_no from sales_order_details;

Output: Product_noP00007P00008P00009

JOINS Simple, Equi-join, Non-Equi join, Self-join, Outer-join

19

Page 20: Chapter 4 Dbms

SQL

The process of forming rows from two or more tables by comparing the contents of a related column is called Joining tables.

The resulting table is called a JOIN between the tables.

Equi Join : A join based on an exact match between two columns is called an Equi Join The comparison operator in the join condition is ‘=’ Example:

Table Name: emp

Ename Eid Sal DeptnoRahul E01 1000 10Vishal E02 1500 15Ajit E03 2000 20

Table Name: dept

Deptno Deptname Location10 Sales Mumbai 15 Accounts Chennai 20 Purchase Mumbai

select ename,eid,location from emp,deptwhere emp.deptno=dept.deptno;

The above join query will retrieve the name, id and location of all employees Output:

Ename Eid LocationRahul E01 Mumbai Vishal E02 Chennai

Types of Joins1. Equi Join2. Non-Equi Join3. Self Join4. Outer Join20

Page 21: Chapter 4 Dbms

SQL

Ajit E03 Mumbai

Non-Equi Join : Joins which use comparison operators other than ‘=’ are called Non-Equi

joins. Example:

Table Name: emp

Ename Eid Sal DeptnoRahul E01 1000 10Vishal E02 1500 15Ajit E03 2000 20

Table Name: dept

Deptno Deptname Location10 Sales Mumbai 15 Accounts Chennai 20 Purchase Mumbai

Select ename, location from emp, deptWhere sal BETWEEN(“operator other than ‘=’”) 1000 AND 2000;

The above join query will retrieve the name, and location of employees having salary between 1000 and 2000

Output:Ename LocationVishal Chennai

Self Join : A join that joins one row in table with another row in the same table is called

Self Join. Using the table alias names these two identical tables can be joined.

From <TableName> [<alias1>], <TableName> [<alias2>]… Example:

Table Name: employee

Eid Ename Manager_noE00001 Rahul E00002E00002 Vishal E00005E00003 Ajit E00004E00004 Prem E00005 Ronak

21

Page 22: Chapter 4 Dbms

SQL

select e1.ename,e2.ename from employee e1,employee e2where e1.manager_no = e2.eid;

The above query will retrieve the names of the employees and the names of their respective manager from the employee table

Output:Ename Manager_noRahul VishalVishal RonakAjit Prem

Outer Join : A join that joins one row in table with another row in the same table is called

Self Join. An Outer Join extends the result of an inner join by including rows from one

table ( say table A ) that don’t have corresponding rows in another table ( say table B ). An important thing to note here is that the outer join operation will not include the rows from table B that don’t have corresponding rows in table A. In other words, an outer join is unidirectional. But there are situations when you may want a bidirectional outer join, i.e., you want to include all the rows from A and B. Rows from the result of the inner join Rows from A that don’t have corresponding rows in B Rows from B that don’t have corresponding rows in A

Let’s look at an example Example:SQL> describe partOutput :-

name null? type --------------------------------------- -------- ---------------------------- PART_ID NOT NULL varchar2(4) SUPPLIER_ID varchar2(4)

SQL> select * from partOutput :-

PART SUPP ------------- --------

P1 S1 P2 S2 P3 P4

SQL> describe supplierOutput :-

name null? type --------------------------------------- -------- ----------------------------

22

Page 23: Chapter 4 Dbms

SQL

SUPPLIER_ID NOT NULL varchar2(4) SUPPLIER_NAME NOT NULL varchar2(20)

SQL> select * from supplierOutput :-

SUPP SUPPLIER_NAME ------------- ------------------------

S1 Supplier#1 S2 Supplier#2 S3 Supplier#3 Above that are two parts (P3 and P4) that don’t have a supplier yet. Also,

there is a supplier (S3) who doesn’t yet supply

Outer join in three types Left outer join Right outer join Full outer join

We have two table (client and salesman) with structure is show below; Table name: Client

NAME IDRahul 10Vishal 20

Table name: Salesman

ID CITY30 bombay20 madras40 bombay

SQL> select * from client

Name Id------------- -----------Rahul 10Vishal 20

SQL> select * from salesman

Id City------------- -----------30 bombay20 madras40 bombay

23

Page 24: Chapter 4 Dbms

SQL

Left outer join

SQL> select * from client LEFT outer join salesman on client.ID = salesman.ID ;

OUTPUT:-NAME ID ID CITY---------- ------ ------ --------vishal 20 20 madrasrahul 10

Using (+) sign left join

SQL> select * from client, salesman where client.ID = salesman.ID(+) ;

Right outer join

SQL> select * from client RIGHT outer join salesman on client.ID = salesman.ID ;

OUTPUT:-NAME ID ID CITY---------- ------ ------ --------vishal 20 20 madras 30 bombay 40 bombay

Using (+) sign Right join

SQL> select * from client, salesman Where client.ID (+) = salesman.ID ;

full outer join

SQL> select * from client FULL outer join salesman on client.ID = salesman.ID ;

OUTPUT:-NAME ID ID CITY---------- ------ ------ --------

24

Page 25: Chapter 4 Dbms

SQL

vishal 20 20 madrasrahul 10

30 bombay 40 bombay

Using (+) sign Full join

SQL> select * from client, salesman where client.ID = salesman.ID(+) unionselect * from client, salesman Where client.ID (+) = salesman.ID ;

Sub Queries Definition: A sub query is a form of SQL statement that appears inside another

SQL statement. It is also know as Nested Query. Sub queries are used in the WHERE and HAVING clause of another SQL

statement The SQL statement in which the sub query is included is called the Main

Query or Outer Query or Parent Query. The parent statement uses the rows returned by the sub query.

A sub query may return a single row or a set of rows Example:

Table Name: emp

Ename Eid Sal DeptnoRahul E01 1000 10Vishal E02 1500 15Ajit E03 2000 20

Table Name: dept

Deptno Deptname Location10 Sales Mumbai 15 Accounts Chennai 20 Purchase Mumbai

Find location of employee having eid ‘E02’

Select location from deptWhere deptno = (select deptno from emp

Where eid=’E02’); Output: Chennai

25

Page 26: Chapter 4 Dbms

SQL

The above query returns a single row

Find the name and id of employees who work in ‘mumbai’

Select ename, eid from emp WHERE deptno IN( select deptno from dept where location=’Mumbai’);

Output:Ename Eid Rahul E01Ajit E03

Types of Sub Queries Multiple Sub query Correlated sub queries

Multiple Sub query: In multiple sub queries the WHERE clause may contain any combination

of ordinary conditions and sub queries These can be connected with AND or OR. Example:

Select ename, eid from empWhere deptno IN(select deptno from dept where location=’Mumbai’)OR(select deptno from dept where deptname = ‘sales’);

The above query returns the name and id of employees who either work in ‘Mumbai’ city work in ‘sales’ department

Correlated sub queries : In correlated sub queries, each execution of the subquery is correlated with

the value of filed in one of the main query’s rows Example:

Select ename,sal,deptno from emp rahulWhere sal in (select AVG(sal) from emp where deptno = rahul.deptno);

The above query returns all employees who earn more than the average salary of employees in their own department.

26

Page 27: Chapter 4 Dbms

SQL

REVIEW QUESTION 1) Explain to the data type.2) Explain Database Language.3) Explain DDL (Data-Definition Language)

OR CREATE, ALTER, TRUNCATE, DROP TABLE.

4) Explain DML (Data-Manipulation language) OR INSERT, SELECT, UPDATE, DELETE.

5) Explain Arithmetic Operators and logical Operators.6) Explain Date functions

OR ADD-MONTHS,MONTHS-BETWEEN, ROUND, NEXTDAY,

TRUNCATE, GREATEST, NEW-TIME.7) Explain Numeric functions. OR

ABS,CEIL,COS,COSH,EXP,FLOOR, POWER, MOD, ROUND, TRUNC, SQRT.

8) Explain Character functions OR

INITCAP,LOWER,UPPER,LTRIM,RTRIM,TRANSLATE,REPLACE,SUBSTRING.

9) Explain Conversion function. OR TO-CHAR,TO-DATE,TO-NUMBER.

10) Explain Miscellaneous functions. OR UID,USER,NVL,VSIZE.

11) Explain Group functions OR Avg.Min,Max,Sum,Count.

12) Explain Decode.13) Explain to Group by, Having and Order by clause.14) Explain Set operators OR

Union, union all, Intersect, Minus.

15) Explain Joins OR Simple Equi-

join,Non-equi,Self-join,Outer-join.16) Explain Sub queries.17) Explain types of sub queries

OR Multiple, Correlated.

27