sql introduction notes

54
8/12/2019 SQL Introduction notes http://slidepdf.com/reader/full/sql-introduction-notes 1/54

Upload: dineshatluri

Post on 03-Jun-2018

234 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 1/54

Page 3: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 3/54

DBMS : Database Management System

DBMS is a system that is used to store and managedata.

A database system consists of two parts namely,Database Management System that organises andmaintains the information whereas the DatabaseApplication is the program that lets us view, retrieve andupdate information stored in the DBMS.

It is a set of programs that is used to store andmanipulation data. Manipulation of data.

A DBMS provides various functions like data security,data integrity, data sharing, data concurrence, data

independence, data recovery etc.

Page 4: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 4/54

Page 5: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 5/54

DATABASE MODELSTwo major Categories of Database models(1) Object – Based Logical Models(2) Record – Based Logical Models

Record based model describes the data structuresand access techniques of a DBMS.Four types of record based logical models are(1) File management System(2) Hierarchical database system(3) Network database system(4) The relational database system

The Object Relational Model supports both objectoriented and relational concepts.

Objects are reusable software codes.

Page 6: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 6/54

Relational Algebra• A set of operators used to perform operations on

tables is called as relat ional algeb ra . Operators inrelational algebra take one or more tables asparameters and produce one table as the result.

• The following are operators in relational algebra: Union, Intersection, Difference or minus, Project, Select, Join

Page 7: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 7/54

Diagrammatic Presentation

Page 8: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 8/54

Introduction to Oracle

Oracle products are based on a concept known as„Client/Server Technology‟.

Tools of Oracle

SQL * Plus• PL/SQL• Forms• Reports

Page 9: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 9/54

Terms and Meanings

• Relation : Table• Tuple : Row• Attribute : Column

Page 10: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 10/54

Structured Query Language (SQL)

• Standard Language for RDBMS• Non Procedural Language

Four Major categories of SQL commands

• DDL (Data Definition Language)• DML (Data Manipulation Language)• DCL (Data Control Language)• TCL (Transaction Control Language)

Page 11: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 11/54

Oracle Internal Data Types

CharacterChar – fixed length character string (1-2000 bytes)

Varchar2 – variable length character string (1-4000 bytes)

Long – variable length character (2GB)

Number – 0,+,-,fixed point, floating point (precision:1-38,scale:-84-127)

Date – stores date and time (Default data type is “dd -mon- yy”)

Raw – stores byte oriented data like binary data (2000 bytes)

Long Raw – stores binary data of variable length (2GB)

LOB – Large object data type (4GB)

CLOB – character objects with single byte charBLOB – binary objects (graphics, video,sound clips)BFILE – file pointers to LOB’s external to Database

Page 12: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 12/54

ORACLE SQL COMMANDS

For Oracle SQL Syntax, visit sitehttp://www.ss64.com

Page 13: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 13/54

BASIC COMMANDS

• DDL – DATA Definition Language commands(create, alter, drop, truncate, comment, rename)

DML – DATA Manipulation Language commands

(select, insert, update, delete, merge, call, explain plan,lock table)

DCL – DATA Control Language commands

(grant, revoke)

• TCL – TRANSACTION Control Language commands(commit, savepoint, rollback, set transaction)

Page 14: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 14/54

CREATE : Genrates table in Oracle database.

CREATE TABLE <table name> (column datatype [defaultexpr] [, …]);

CREATE TABLE <table name> [(column, column…)] ASsubquery;

CREATE TABLE <table name> (column1 datatype,

column2 datatype [constraint constraint name constrainttype] …);

Example :CREATE TABEL team (e_id varchar2(10), e_name varchar2(50), ext_novarchar2(15), mobile_no varchar2(20), cubicle_no number(5), email_idvarchar2(35), ip_address varchar2(15),att_uid varchar2(10),intranet_pin number(5), location varchar2(30),date_of_birth date);

TEAM

E_ID E_NAME EXT_NO MOBILE_NO CUBICLE_NO EMAIL_ID IP_ADDRESS ATT_UID INTRANET_PIN LOCATION DATE_OF_BIRTH

Page 15: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 15/54

ALTER : Modifies table structure• A new column to be added in the table.• Change the width of datatype or the datatype itself• Include or drop integrity constraints

ALTER TABLE <table name> MODIFY (columndefinition…);

ALTER TABLE <table name> ADD (column definition…);

Example :ALTER TABLE team ADD dbor_ph_no number(5);ALTER TABLE team ADD team_desc varchar2(25);

TEAM E_ID E_NAME EXT_NO MOBILE_NO CUBICLE_NO EMAIL_ID IP_ADDRESS ATT_UID INTRANET_PIN LOCATION DATE_OF_BIRTH DBOR_PH_NO TEAM_DESC

Page 16: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 16/54

TRUNCATE : Permanent deletion of ALL Records in Table• Deletes all records from table.• Oracle internally reclaims the space of the deleted

rows for future use.TRUNCATE table table name;TRUNCATE table table name

reuse storage;

DESC : Describes table structureTo view the structure of the table.

DESC <table name>;Example

DESC team;

TEAM

E_ID E_NAME EXT_NO MOBILE_NO CUBICLE_NO EMAIL_ID IP_ADDRESS ATT_UID INTRANET_PIN LOCATION DATE_OF_BIRTH DBOR_PH_NO TEAM_DESC

Before Truncate

PROJECTS_ATT

P_NO PMT_CODE P_NAME

PA876 289590 CCI

P3A49 290398 PORT_TO_EQP

P9370

P9187

PA569

PROJECTS_ATT

P_NO PMT_CODE P_NAME After Truncate

Page 17: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 17/54

DROPIt removes table along with its contents permanently.It commits automatically. (auto commit)

DROP table <table name>

Example

PROJECTS_ATT P_NO PMT_CODE P_NAME

PA876 289590 CCI

P3A49 290398 PORT_TO_EQP

P9370

P9187

PA569

SQL> drop table projects_att;

Table dropped.

SQL> desc projects_att;ERROR:ORA-04043: object projects_att does not exist

SQL>

Before Drop After Drop

Page 18: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 18/54

SELECTTo query the table, select comand is used. Request forinormation stored in a table can be done through select

command.

SELECT fieldsFROM table name

WHERE conditionsGROUP BYHAVINGORDER BY;

SELECT column name <alias name> FROM <table name>;

Page 19: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 19/54

SELECT * FROM team;

TEAM

E_ID E_NAME EXT_ NO MOBILE_NO CUBICLE_ NO EMAIL_ID IP_ADDRESS ATT_UID INTRANET _PIN LOCATION DATE_OF_BIRTH

DBOR

_PH_NO TEAM_DESC

C7770 Baby Rani 2479 9860039148 2195 [email protected] DSCP14407 bk2672

Giga SpaceDelta 12/10/1984 3 PL SQL DEVELOPER

24157 Prashant Achari 2478 9890313073 2002 [email protected] DSCP14371 pa7300

Giga SpaceDelta 3/31/1973 3 PL SQL DEVELOPER

24122 GauriBahadarpurkar 2478 9850570278 2205

[email protected] DSCP14374 gb1305

Giga SpaceDelta 3/12/1980 3 PL SQL DEVELOPER

24459 Lalita Marathe 2485 9890933403 2193 [email protected] DSCP14370 lm8718

Giga SpaceDelta 12/13/1967 3 PL SQL DEVELOPER

9891 RashmiMohankar 2479 9890474510 2194

[email protected] DSCP14430 rx2289

Giga SpaceDelta 5/28/1975 3 PL SQL DEVELOPER

24530 VinayakVasmatkar 2496 9823454512 2201

[email protected] DSCP14390 vv9355

Giga SpaceDelta 5/14/1980 3 PL SQL DEVELOPER

C8210 PrashadDeshmukh 2478 9890460043 2203

dprashad@techmahindr a.com DSCP14409 pd5446

Giga SpaceDelta 1/27/1983 3 PL SQL DEVELOPER

25736

Purusharth

Upadhyay 2478 9881124287 2204

purusharth@techmahin

dra.com DSCP14501 pu7924

Giga Space

Delta 1/5/1982 3 PL SQL DEVELOPER

26101 HarshalParulkar 9960049222

harshalvp@techmahindr a.com

Giga SpaceDelta 8/19/1980 3 DBA

20560 Vishal Sawant 9890499748 [email protected]

Giga SpaceDelta 8/25/1979 3 DBA

26114 Manoj Shardul 9850304527 [email protected]

Giga SpaceDelta 11/14/1976 3 DBA

Page 20: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 20/54

Simple SQL Query

PName Price Category Manufacturer

Gizmo $19.99 Gadgets GizmoWorks

Powergizmo $29.99 Gadgets GizmoWorks

SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Hitachi

SELECT *FROM ProductWHERE category=„Gadgets‟

Product

PName Price Category Manufacturer

Gizmo $19.99 Gadgets GizmoWorks

Powergizmo $29.99 Gadgets GizmoWorks“selection”

Page 21: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 21/54

Simple SQL Query – Selection, projection

PName Price Category Manufacturer

Gizmo $19.99 Gadgets GizmoWorks

Powergizmo $29.99 Gadgets GizmoWorks

SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Hitachi

SELECT PName, Price, ManufacturerFROM Product

WHERE Price > 100

Product

PName Price Manufacturer

SingleTouch $149.99 Canon

MultiTouch $203.99 Hitachi

“selection” and “projection”

Page 22: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 22/54

The WHERE Clause• Numerical and string comparison

!=,<>,=, <, >, >=, <=,between (between val1 AND val2 )

• String comparison is according to the lexicographic

orderingThe Expected conversion between CHAR and VARCHAR

• Logical components: AND, OR, NOT

• Null verification: IS NULL, IS NOT NULL• For dates and times, what you expect...Pattern matching on strings...

Page 23: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 23/54

Example :

SELECT sname FROM sailors

WHERE age >= 40 and rating IS NOT NULL;

The Like Operator• s LIKE p: pattern matching on strings

• p may contain two special symbols: – % = any sequence of characters – _ = any single character

Product (PName, Price, Category, Manufacturer)Find all products whose name mentions „gizmo‟:

SELECT *FROM ProductsWHERE PName LIKE „%gizmo%‟

Page 24: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 24/54

Eliminating Duplicates

SELECT DISTINCT categoryFROM Product

Compare to:

SELECT categoryFROM Product

Category

Gadgets

Gadgets

Photography

Household

CategoryGadgets

Photography

Household

Page 25: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 25/54

Ordering the Results

SELECT category

FROM ProductORDER BY pname

PName Price Category Manufacturer

Gizmo $19.99 Gadgets GizmoWorks

Powergizmo $29.99 Gadgets GizmoWorks

SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Hitachi?

SELECT DISTINCT categoryFROM ProductORDER BY category

Category

Gadgets

Household

Photography

Page 26: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 26/54

Joins in SQL• Connect two or more tables

PName Price Category ManufacturerGizmo $19.99 Gadgets GizmoWorks

Powergizmo $29.99 Gadgets GizmoWorks

SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Hitachi

Product

Company

Cname StockPrice Country

GizmoWorks 25 USA

Canon 65 Japan

Hitachi 15 Japan

What isthe connection

betweenthem ?

Page 27: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 27/54

Joins

Product (pname, price, category, manufacturer)Company (cname, stockPrice, country)

Find all products under $200 manufactured in Japan;return their names and prices.

SELECT pname, priceFROM Product, CompanyWHERE manufacturer=cname AND country=„Japan‟

AND price <= 200

Joinbetween Product

and Company

Page 28: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 28/54

Joins in SQL

PName Price Category Manufacturer

Gizmo $19.99 Gadgets GizmoWorks

Powergizmo $29.99 Gadgets GizmoWorks

SingleTouch $149.99 Photography Canon

MultiTouch $203.99 Household Hitachi

Product Company

Cname StockPrice Country

GizmoWorks 25 USA

Canon 65 Japan

Hitachi 15 Japan

PName Price

SingleTouch $149.99

SELECT pname, priceFROM Product, Company

WHERE manufacturer=cname AND country=‘Japan’ AND price <= 200

Page 29: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 29/54

Schema Used in Examples

Page 30: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 30/54

• SQL includes a between comparison operator• E.g. Find the loan number of those loans with loan

amounts between $90,000 and $100,000 (that is,$90,000 and $100,000)(i.e. inclusive)select loan-nu m ber

from loan where a m o u n t between 90000 and 100000

• E.g. Find the loan number of those loans with loanamounts equal to $90000, $100000, $ 110000 or$120000

• SQL also includes an in operator used for setinclusion testingselect loan-nu m ber

from loan where a m o u n t in (90000, 100000, 110000, 120000)

Page 31: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 31/54

Ambiguous Names and Aliasing• SQL allows renaming relations and attributes using

the as clause:old-name as new-nam e

• Find the name, loan number and loan amount of allcustomers; rename the column name loan-number as

loan-id.select cus to m er-name, b or row er.loan-num ber asloan- id , amo un tfrom bo rrow er, loan

where bo rrow er.loan-nu m ber = loan.loan-num ber

Page 32: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 32/54

Aggregate Functions• These functions

avg: average valuemin: minimum valuemax: maximum valuesum: sum of valuescount: number of values

• Produce numbers• Find the average account balance at the Fargo branch.select avg (balance) from accoun t w here branc h-name =

“Fargo”;

• Find the number of tuples in the cus tomer relation.

select count (*) from customer;

Find the distinct number of depositors in the bank.

select count (distinct customer-name) from depos i tor ;

Page 33: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 33/54

Find the average account balance at the Fargo branch.

Find the distinct number of depositors in the bank.

Find the number of tuples in the cus tomer relation.

select avg (balance) from accoun twhere branc h-name = “Fargo”

select count (*)from cus tomer

select count (distinct customer-name)from depos i tor

Page 34: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 34/54

INSERTIt adds one or more rows to a table.

INSERT INTO <table name> VALUES (a list of data values);

Example : INSERT INTO project_master (p_no, pmt_cd, tm_attuid)

VALUES („PA876‟,‟289590‟,‟rx2289‟);

INSERT INTO project_master values („P3A49‟, ‟290398‟,‟pa7300‟);

PROJECT_MASTER

P_NO PMT_CODE TM_ATTUID

PA876 289590 rx2289

P3A49 290398 pa7300

After Insert

PROJECT_MASTER

P_NO PMT_CODE TM_ATTUID

Before Insert

Page 35: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 35/54

DELETE

To delete single or multiple records from a table.

DELETE FROM <table name> WHERE [condition …]; Example :

DELETE FROM project_master WHERE p_no = „PA876‟;

PROJECT_MASTER P_NO PMT_CODE TM_ATTUID

PA876 289590 rx2289

P3A49 290398 pa7300

PROJECT_MASTER P_NO PMT_CODE TM_ATTUID

P3A49 290398 pa7300

Before Delete After Delete

Page 36: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 36/54

UPDATETo update / modify contents in rows of a table.

UPDATE <table name> SET field = value,… WHEREcondition;

Example :UPDATE project_master set pmt_code = „123456‟ WHERE p_no = „P9370‟;

PROJECTS_ATT

P_NO PMT_CODE P_NAME

PA876 289590 CCI

P3A49 290398 PORT_TO_EQPP9370

P9187

PA569

PROJECTS_ATT

P_NO PMT_CODE P_NAME

PA876 289590 CCI

P3A49 290398 PORT_TO_EQPP9370 123456

P9187

PA569

Before Update After Update

Page 37: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 37/54

Page 38: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 38/54

Integrity Constraints in Create Table

• not null (after domain)• Unique (after domain) • primary key ( A1, ..., An )• foreign Key

• Create table Table_YYY(A1 char(3),A2 int,A3 int UNIQUE,A4 float NOT NULL,PRIMARY KEY(A1,A2),FOREIGN KEY (A1) REFERENCESTABLE_XXX(A1) ON DELETE CASCADE ONUPDATE CASCADE);

Page 39: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 39/54

Nested Sub-queries• Some queries require that existing values in the DB be

fetched and then used in a comparison condition• SQL provides a mechanism for the nesting of sub-

queries.• A sub-query is a select-from-where expression that is

nested within another query (called outer query)• A common use of sub-queries is to perform tests for

set membership, set comparisons, and set cardinality.

Example Find all customers who have both an account and a loan

at the bank.select customer-name f rom borrowerw here customer-name in

(select customer-name from depositor );

Page 40: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 40/54

VIEWS

VIEW

CREATE [or REPLACE] [[no] [force] view <view name>[column alias name…] as <query> [with [check option][read only] [constraint]];

Example :CREATE VIEW ven_view AS SELECT * FROM

VENDOR_MASTER;

CREATE VIEW pen_view AS SELECT * FROMorder_master WHERE o_status = „p‟;

TYPES OF JOINS JOB GRADES

Page 41: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 41/54

TYPES OF JOINS

• Equijoin• Non-equijoin• Outer join• Self join

Tables used

_

GRADE_LEVEL LOWEST_SAL HEIGHEST_SAL

A 1000 2999

B 3000 5999

C 6000 9999

EMPLOYEES

EMPLOYEE_ID LAST_NAME FIRST_NAME DEPARTMENT_ID SALARY MANAGER_ID JOB_ID

C7770 Komarapu Baby Rani 10 3100 24459 IT_PROG

24157 Achari Prashant 10 7900 12345 IT_PROG

24122 Bahadarpurkar Gauri 10 4500 24459 IT_PROG

24459 Marathe Lalita 10 2500 12345 IT_PROG

9891 Mohankar Rashmi 10 5500 24459 IT_PROG

24530 Vasmatkar Vinayak 10 4000 24459 IT_PROG

C8210 Deshmukh Prashad 10 2500 24459 IT_PROG

25736 Upadhyay Purusharth 10 2500 24459 IT_PROG

26101 Parulkar Harshal 20 7500 24459 IT_DBA

20560 Sawant Vishal 20 4500 24459 IT_DBA

26114 Shardul Manoj 20 4000 24459 IT_DBA

12345 Shankar Murali 40 9000 54321 IT_CONSULTANT

DEPARTMENT

DEPARTMENT_ID DEPARTMENT_NAME LOCATION

10 DESIGN BETA

20 DEVELOPMENT DELTA

30 TESTING GAMMA

Equijoins

Page 42: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 42/54

Equijoins • Equijoins are based on common column in the two

tablesIt is also called as simple joins or inner joins

ExampleSELECT a.employee_id, a.last_name,a.department_id, b.location_id

FROM employees a, departments bWHERE a.department_id = b.department_id;

EMPLOYEE_ID LAST_NAME DEPARTMENT_ID LOCATION

C7770 Komarapu 10 BETA

24157 Achari 10 BETA

24122 Bahadarpurkar 10 BETA

24459 Marathe 10 BETA

9891 Mohankar 10 BETA

24530 Vasmatkar 10 BETA

C8210 Deshmukh 10 BETA

25736 Upadhyay 10 BETA

26101 Parulkar 20 DELTA

20560 Sawant 20 DELTA

26114 Shardul 20 DELTA

Non Equijoins

Page 43: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 43/54

Non-EquijoinsA non-equijoin is a join condition containingsomething other than an equality operatorsuch as <=, >=, between.Example

SELECT e.last_name , e.salary, j.grade_levelFROM employees e , job_grades jWHERE e.salary between

j.lowest_sal and j.heighest_sal;LAST_NAME SALARY GRADE_LEVEL Komarapu 3100 B

Achari 7900 C

Bahadarpurkar 4500 B

Marathe 2500 A

Mohankar 5500 B

Vasmatkar 4000 B Deshmukh 2500 A

Upadhyay 2500 A

Parulkar 7500 C

Sawant 4500 B

Shardul 4000 B

Shankar 9000 C

O t j i

Page 44: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 44/54

Outer-join You use an outer join to see rows that do not meet the join condition.

The Outer join operator is the plus sign(+).The missing rows can be returned if an Outer joinoperator is used in the join condition.

Example

SELECT e.last_name,e.department_id,d.department_name

FROM employee e,departments d

WHERE e.department_id(+)= d.department_id;

LAST_NAME DEPARTMENT_ID DEPARTMENT_NAME

Komarapu 10 DESIGN

Achari 10 DESIGN

Bahadarpurkar 10 DESIGN

Marathe 10 DESIGN

Mohankar 10 DESIGN

Vasmatkar 10 DESIGN

Deshmukh 10 DESIGN

Upadhyay 10 DESIGN

Parulkar 20 DELTA

Sawant 20 DELTA

Shardul 20 DELTA

GAMMA

S lf J i

Page 45: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 45/54

Self-JoinsIf the join is on the same table it is called Self join.Example:

SELECT worker.last_name || ‟works for‟ || manager.last_name

FROM employees worker, employees managerWHERE worker.manager_id =

manager.employee_id; worker Manger

Komarapu Marathe

Achari Shankar

Bahadarpurkar Marathe

Marathe Shankar

Mohankar Marathe

Vasmatkar Marathe

Deshmukh Marathe

Upadhyay Marathe

Parulkar Marathe

Sawant Marathe

Shardul Marathe

Shankar

Page 46: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 46/54

SUBQUERY SYNTAXSELECT select_list

FROM tableWHERE expr operator ( SELECT select_list

FROM table);The subquery executes once before the main query.The result of the subquery is used by the main query.

ExampleSELECT last_name, first_name, employee_id

FROM employeesWHERE salary > ( SELECT salary

FROM employeesWHERE upper(last_name) =

„MOHANKAR‟);

LAST_NAME FIRST_NAME EMPLOYEE_ID

Achari Prashant 24157

Parulkar Harshal 26101

Shankar Murali 12345

Page 47: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 47/54

E l

Page 48: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 48/54

Example :SELECT last_name, department_id, salary

FROM employees

WHERE department_id = (SELECT department_idFROM employeesWHERE employee_id =

24459)and salary > (SELECT salary

FROM employees

WHERE employee_id = 24122);

LAST_NAME DEPARTMENT_ID SALARY

Mohankar 10 5500

Achari 10 7900

Page 49: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 49/54

Page 50: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 50/54

The Having Clause with Subqueries

1. The Oracle server executes subqueries first.

2. The Oracle server returns results into the havingclause of the main query.

Example

Select department_id , min(salary)From employeesGroup by department_id

Having min(salary) > ( select min(salary)from employeeswhere department_id = 10);

DEPARTMENT_ID SALARY 20 4000

40 9000

M l i l R S b i

Page 51: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 51/54

Multiple-Row Subqueries

1. Return more than one row.

2. Use multiple-row comparison operators

Operator Meaning

IN Equal to any member in the list

ANY Compare value to eachValue returned by the subquery

ALL Compare value to every value returned by the subquery

M lti l R S b i i IN t

Page 52: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 52/54

Multiple Row Subqueries using IN operator

Select last_name, salary,department_id

From employeesWhere salary IN ( select min (salary)

from employeesgroup by department_id );

LAST_NAME SALARY DEPARTMENT_ID

Marathe 2500 10

Deshmukh 2500 10

Upadhyay 2500 10

Shardul 4000 20

Shankar 9000 40

Page 53: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 53/54

Using the ALL Operator in Multiple-Row subqueriesSELECT employee_id , last_name , job_id, salary

FROM employeesWHERE salary > ALL ( SELECT salary

FROM employeesWHERE job_id = „IT_PROG‟)

and job_id <> „IT_PROG‟;

EMPLOYEE_ID LAST_NAME JOB_ID SALARY

12345 Shankar IT_CONSULTANT 9000

Using the ANY Operator in Multiple-Row subqueries

Page 54: SQL Introduction notes

8/12/2019 SQL Introduction notes

http://slidepdf.com/reader/full/sql-introduction-notes 54/54

Using the ANY Operator in Multiple-Row subqueries SELECT employee_id , last_name , job_id , salary

FROM employeesWHERE salary > ANY ( SELECT salary

FROM employeesWHERE job_id = „IT_PROG‟)

and job_id <> „IT_PROG‟;

EMPLOYEE_ID LAST_NAME JOB_ID SALARY

26101 Parulkar IT_DBA 7500

20560 Sawant IT_DBA 4500

26114 Shardul IT_DBA 4000

12345 Shankar IT_CONSULTANT 9000

EMPLOYEES

EMPLOYEE_ID LAST_NAME FIRST_NAME DEPARTMENT_ID SALARY MANAGER_ID JOB_ID

C7770 Komarapu Baby Rani 10 3100 24459 IT_PROG

24157 Achari Prashant 10 7900 12345 IT_PROG

24122 Bahadarpurkar Gauri 10 4500 24459 IT_PROG

24459 Marathe Lalita 10 2500 12345 IT_PROG

9891 Mohankar Rashmi 10 5500 24459 IT_PROG

24530 Vasmatkar Vinayak 10 4000 24459 IT_PROG

C8210 Deshmukh Prashad 10 2500 24459 IT_PROG

25736 Upadhyay Purusharth 10 2500 24459 IT_PROG

26101 Parulkar Harshal 20 7500 24459 IT_DBA

20560 Sawant Vishal 20 4500 24459 IT_DBA

26114 Shardul Manoj 20 4000 24459 IT_DBA