Chapter 6 SQL: Data Manipulation (Advanced Commands) Pearson Education © 2009.
SQL 3. 1 CSE2132 Database Systems Week 3 Lecture SQL Data Manipulation.
-
Upload
barbra-golden -
Category
Documents
-
view
220 -
download
1
Transcript of SQL 3. 1 CSE2132 Database Systems Week 3 Lecture SQL Data Manipulation.
SQL 3. 1
CSE2132 Database Systems
Week 3 Lecture
SQL Data Manipulation
SQL 3. 2
SQL - Structured Query LanguageOriginally designed and implemented by IBM research as the
interface
to a relational database. It is used by Oracle for all interaction with the database.
ANSI Standard SQL-92 defines three levels of compliance, Entry, Intermediate, and Full. Oracle conforms to Entry level compliance, and has many features that conform to Intermediate or Full level compliance. SQL-99 extended SQL-92(Core SQL-99) to a newer object relational form.
A declarative language.
The DBMS performs retrieval. A choice of access routines is made to optimize the query.
SQL specifies syntax features for retrieval update and definition of
the database.
SQL 3. 3
PNAMENUTBOLTCARAVAN
PARTNOP1P2P3
PRICE$0.20$1.00$5000.00
QOH20403
PART
SELECT pname, price*qoh AS pvalue
FROM PART
WHERE price > 0.20 AND price * qoh > 30.0
ORDER BY pname desc;pnameCARAVANBOLT
pvalue$15,000.00$40.00
Example of a Simple SELECT
SQL 3. 4
Further Examples of SELECT
SELECT * FROM PART;
Selects all column values for all rows
SELECT PARTNO, PNAME FROM PART
WHERE PRICE BETWEEN 0.2 AND 1.0;
Selects rows where price ge .2 and le 1.0
SELECT PARTNO, PNAME FROM PART
WHERE PNAME IN ('NUT','BOLT');
Selects rows where pname has a value in the following list
SQL 3. 5
SQL SELECT Statement
SELECT [ALL|DISTINCT]
expression[AS result_column]
{,expression[AS result_column]}
FROM tablename[t_alias]
{,tablename[t_alias]}
[WHERE search_condition]
[GROUP BY colname {,colname}]
[HAVING search_condition]
Nb: This is the syntax of a subselect
SQL 3. 6
The full syntax is then:
subselect
{UNION [ALL] subselect}
[ORDER BY colname[ASC|DESC]
{,colname [ASC|DESC] } ]
Nb: that the search condition in a subselect may be a subselect
SQL SELECT Statement
SQL 3. 7
SQL - Sample DB Schema
PM_NAME BIRTH_YR YRS_SERVED DEATH_AGE STATE_BORN STATE_REP
PRIME _MINISTER
MARRIAGEPM_NAME SPOUSE_NAME MAR_YR PM_AGE NR_CHILDREN
MINISTRY
MIN_NR PM_NAME PARTY DAY_COMM MTH_COMM YR_COMM
SQL 3. 8
Expressions in SELECT
Arithmetic operators are + - ** * /
Comparison operators are = != <> ^= > < >= <=
Logical operators are AND OR NOT
Parentheses may be used to alter order of evaluation - unary, **, * /, + -
Wildcard % = any string of zero or more character
_ = any one character
[ ] = any of the characters enclosed in brackets
A range of numeric, string, date and other functions are available.
SQL 3. 9
Arithmetic Operators in a SELECT
List the name, birth year and year of death of each prime minister who was born in New South Wales. List in order of birth year.
SELECT PM_NAME, BIRTH_YR, BIRTH_YR + DEATH_AGEFROM PRIME_MINISTERWHERE STATE_BORN = ‘NSW’ORDER BY BIRTH_YR
PM_NAME BIRTH_YR BIRTH_YR + DEATH_AGEBarton E 1849 1920Page E C G 1880 1961Chifley J 1885 1951Holt H E 1908 1967McMahon W 1908 ?Whitlam E G 1916 ?
SQL 3. 10
Using the Logical Operators
Which prime ministers were born in Victoria before the turn of the century?
SELECT PM_NAME, BIRTH_YR, STATE_BORNFROM PRIME_MINISTERWHERE STATE_BORN=‘VIC’ AND BIRTH_YR < 1900
PM_NAME BIRTH_YR STATE_BORNDeakin A 1856 VICBruce S M 1883 VICScullin J H 1876 VICMenzies R G 1894 VICCurtin J 1885 VIC
SQL 3. 11
Combining Logical Operators
Which prime ministers were born in NSW and then represented Victoria or have simply not served less than two years?
SELECT PM_NAME, STATE_BORN, STATE_REP, YRS_SERVEDFROM PRIME _MINISTERWHERE STATE_REP = ‘VIC’AND STATE_BORN = ‘NSW’OR NOT YRS_SERVED < 2
PM_NAME STATE_BORN STATE_REP YRS_SERVEDHolt H E NSW VIC 1.88Gorton J G VIC VIC 3.17Whitlam E G NSW NSW 2.92Fraser J M VIC VIC 7.33
SQL 3. 12
Further Examples of SELECT
SELECT PNAME FROM PART
WHERE QOH IS NULL;
Selects those rows where qoh has a null value
SELECT * FROM PART
WHERE PNAME LIKE '_ _T' or PNAME LIKE '%LT';
Selects rows where pname has three letters the last of which is a T or PNAME ends in LT
SQL 3. 13
Use of COUNT with DISTINCT
How many liberal prime ministers were commisioned between 1970 and 1980?
SELECT ‘Liberal PMs’, COUNT(*), COUNT(DISTINCT PM_NAME)FROM MINISTRYWHERE PARTY = ‘Liberal’AND YR_COMM BETWEEN 1970 AND 1980
COUNT(*) COUNT(DISTINCT PM_NAME)
Liberal PMs 5 2
SQL 3. 14
UNION
PNAMENUTBOLTCARAVAN
PARTNOP1P2P3
PRICE$0.20$1.00$5000.00
QOH21403
PART
SELECT pname, 'q1' AS Query FROM PART WHERE QOH < 22
UNION
SELECT pname, 'q2' AS Query FROM PART WHERE QOH > 20;
NUTCARAVANNUTBOLT
q1q1q2q2
pname Query
SQL 3. 15
DELETE FROM tablename [t_alias]
[ WHERE search-condition ]
Delete one or many rows in a table.
In general search-condition and qualification may not involve a sub select on tablename.
DELETE FROM PART WHERE qoh < 4.00;
DELETE
SQL 3. 16
UPDATE
UPDATE tablename [t_alias]
SET colname = expression { , colname = expression}
[ WHERE search_condition ]
Replaces values of the specified columns with expression values for all rows satisfying the search-condition.
Expressions in the set clause may be constants, column values or subqueries.
UPDATE PART
SET price = price * 1.1
WHERE price < 20;
SQL 3. 17
Set Functions in SELECT
PNAMENUTBOLTCARAVAN
PARTNOP1P2P3
PRICE$1.00$1.00$5000.00
QOH20203
PART
Part_count3
Av_price$1667.33
Set functions supported = avg count max min sum
Set functions may not be used directly in a search condition
Price_count2
SELECT count(partno) AS Part_count, avg(price) AS Av_price, count(distinct price) AS Price_count FROM part
SQL 3. 18
Use of GROUP BY
List the number of prime ministers from each party.
SELECT PARTY, COUNT(*)FROM MINISTRYGROUP BY PARTY
PARTY COUNT(*)Country 3Free Trade 1Labor 15Liberal 17National Labor 1Nationalist 3Proctectionist 4United Australia 5
SQL 3. 19
Grouping by More Than One Column
Group prime ministers by their state born and the state they represented. Give the number of prime ministers and the total of years served.
SELECT STATE_BORN, STATE_REP, COUNT(*), SUM(YRS_SERVED)FROM PRIME_MINISTERGROUP BY STATE_BORN, STATE_REP
STATE_BORN STATE_REP COUNT(*) SUM(YRS_SERVED)? NSW 4 9.67? QLD 1 4.81NSW NSW 5 11.83NSW VIC 1 1.88QLD QLD 2 0.13TAS TAS 1 7.25VIC VIC 7 42.69VIC WA 1 3.75
SQL 3. 20
Grouping With the WHERE Clause
For prime ministers born after 1900, list the number of prime ministers born in each state and the total number of years served.
SELECT STATE_BORN, COUNT(*), SUM(YRS_SERVED)FROM PRIME_MINISTERWHERE BIRTH_YR > 1900GROUP BY STATE_BORN
STATE_BORN COUNT(*) SUM(YRS_SERVED)WA 1 ?VIC 2 10.50NSW 3 6.52
SQL 3. 21
Grouping With the HAVING Clause
For each state where the total years served by prime ministers born in that state is less than 10 years, give the number of prime ministers born in that state and the total number of years served.
SELECT STATE_BORN, COUNT(*), SUM(YRS_SERVED)FROM PRIME_MINISTERGROUP BY STATE_BORNHAVING SUM(YRS_SERVED) < 10
STATE_BORN COUNT(*) SUM(YRS_SERVED)TAS 1 7.25QLD 2 0.13
SQL 3. 22
SELECT partno,Count(suppno) AS Supp_count,Sum(qty_supp) AS Total_qty
FROM part_supplier
GROUP BY partno
HAVING count(suppno) > 1PARTNOP1
SUPP_COUNT2
TOTAL_QTY40
PARTNOP1P2P1P3
SUPPNOS1S1S2S2
QTY_SUPP20302010
PART_SUPPLIER
Grouping With the HAVING Clause
SQL 3. 23
Subqueries
Give the name and death age for each prime minister who died at an age less than the average death age of prime ministers.List in ascending order of death age.
SELECT PM_NAME, DEATH_AGEFROM PRIME_MINISTERWHERE DEATH_AGE < (SELECT AVG(DEATH_AGE) FROM PRIME_MINISTER)ORDER BY DEATH AGE
PM_NAME DEATH_AGEHolt H E 59Lyons J A 60Curtin J 60Deakin A 63
SQL 3. 24
Subqueries
Which prime minister died the oldest? Give his name and that age.
SELECT PM_NAME, DEATH_AGEFROM PRIME_MINISTERWHERE DEATH_AGE = (SELECT MAX(DEATH_AGE) FROM PRIME_MINISTER)
PM_NAME DEATH_AGEForde F M 93
SQL 3. 25
Subquery With IN Operator
SELECT DISTINCT DEPUTY_NAME, PARTYFROM DEPUTY_PMWHERE DEPUTY_NAME IN (SELECT PM_NAME FROM PRIME_MINISTER)
DEPUTY_NAME PARTYChifley J B LaborCook J Free Trade Deakin A Protectionist
List the name and party of each deputy prime minister who was also prime minister.
SQL 3. 26
The ANY Operator
PARTNOP1P2P1P3
SUPPNOS1S1S2S2
QTY_SUPP20302510
PART_SUPPLIER
SELECT partno, suppno, qty_supp FROM Part_supplier
WHERE qty_supp > ANY
(SELECT avg(qty_supp) FROM Part-supplier)
PARTNOP2P1
SUPPNOS1S2
QTY_SUPP3025
SQL 3. 27
Multiple Nested Subqueries
Give the name and birth year of each prime minister who wascommisioned after Bob Hawke had turned 21. Order by birth year.
SELECT PM_NAME, BIRTH_YRFROM PRIME_MINISTERWHERE PM_NAME = ANY (SELECT PM_NAME FROM MINISTRY WHERE YR_COMM > (SELECT BIRTH_YR + 21 FROM PRIME_MINISTER WHERE PM_NAME = ‘Hawke R J L’))AND PM_NAME <> ‘Hawke R J L’ORDER BY BIRTH_YR
SQL 3. 28
SubqueriesSELECT partno, suppno, qty_supp FROM Part_supplier
WHERE qty_supp > ANY
(SELECT avg(qty_supp) FROM Part-supplier)
Subqueries may be used in a number of SQL statements.
select, update, insert, delete, create table,
create view, create permit, create integrity
· Subselects may be nested to several levels.
· Special comparison operators are used in additional to =, <>, >, <, etc to indicate comparison to a set of values:
IN equals one of the values returned by the subselect
ANY true if any value returned meets the condition
ALL true if all values returned meet the condition
SQL 3. 29
Correlated Subqueries
PARTNOP1P2P1P2P3
SUPPNOS1S1S2S2S2
QTY_SUPP2030252010
PART_SUPPLIER
SELECT partno, suppno, qty_supp FROM Part_supplier PS1
WHERE qty_supp > ANY
(SELECT avg(qty_supp) FROM Part-supplier PS2
WHERE PS2.partno = PS1.partno)
PARTNOP1P2
SUPPNOS2S1
QTY_SUPP2530
SQL 3. 30
Correlated Subqueries
SELECT partno, suppno, qty_supp FROM Part_supplier PS1
WHERE qty_supp > ANY
(SELECT avg(qty_supp) FROM Part-supplier PS2
WHERE PS2.partno = PS1.partno)
· Subselects (inner queries) are generally executed once and return a set of values to the outer query.
· With a correlated subselect the outer query passes values to the inner query which then evaluates and returns a set of values to the outer query. This process repeats until the outer query terminates.
Which suppliers are supplying more than the average for a part and how much of that part do they supply?
SQL 3. 31
Joining Tables
EMPNOE1E2E3
ENAMEREDBLUEBROWN
MGRNOE1E1E1
DEPTNOD1D1D2
DEPTNOD1D2D3
DNAMETAXPAYLEAVE
EMP DEP
SELECT e.empno AS Number, e.ename AS Name, d.dname AS Department
FROM emp e, dep d
WHERE e.deptno = d.deptnoNumberE1E2E3
NameREDBLUEBROWN
DepartmentTAXTAXPAY
SQL 3. 32
A Search and Join Condition
For each prime minister born in or after 1900, give his name, birth year and party.
SELECT P.PM_NAME, BIRTH_YR, PARTYFROM PRIME_MINISTER P, MINISTRY MWHERE P.PM_NAME = M.PM_NAME AND BIRTH_YR >= 1900
PM_NAME BIRTH_YR PARTYHolt H E 1908 LiberalHolt H E 1908 LiberalMcEwen J 1900 CountryGorton J G 1911 LiberalGorton J G 1911 LiberalGorton J G 1911 Liberal
SQL 3. 33
Multiple Joins
Give the name, birth year, party and the year of marriage of prime ministers born in or after 1900.
SELECT DISTINCT P.PM_NAME, BIRTH_YR, MAR_YR, PARTYFROM PRIME_MINISTER P,PM_MARRIAGE W,MINISTRY MWHERE P.PM_NAME = W.PM_NAMEAND P.PM_NAME = M.PM_NAMEAND BIRTH_YR >= 1900
PM_NAME BIRTH_YR MAR_YR PARTYFraser J M 1930 1956 LiberalGorton J G 1911 1935 LiberalHawke R J L 1929 1956 LaborHolt H E 1908 1946 LiberalMcEwen J 1900 1921 CountryMcEwen J 1900 1968 Country
SQL 3. 34
EMPNOE1E2E3
ENAMEREDBLUEBROWN
MGRNOE1E1E1
DEPTNOD1D1D2
EMP
SELECT X.empno AS Number, X.ename AS Name, Y.ename AS Manager
FROM emp X, emp Y
WHERE X.mgrno = Y.empno
NumberE1E2E3
NameREDBLUEBROWN
ManagerREDREDRED
Joining a Table To Itself
SQL 3. 35
The EXISTS Operator
List the name, birth year and state represented of prime ministers who were also deputy prime ministers.
SELECT PM_NAME, BIRTH_YR, STATE_REPFROM PRIME_MINISTERWHERE EXISTS (SELECT * FROM DEPUTY_PM WHERE DEPUTY_NAME = PM_NAME)
Nb: The subquery always uses “SELECT *” and here the correlationcolumn is PM_NAME. The condition is satisfied if at least one row exists. PM_NAME BIRTH_YR STATE_REP
Deakin A 1856 VICCook J 1860 NSWHughes W M 1862 NSW
SQL 3. 36
The NOT EXISTS Operator
Give the name, state represented and death age of each prime minister who has no recreations.
SELECT PM_NAME, BIRTH_YR, DEATH_AGEFROM PRIME_MINISTER PWHERE NOT EXISTS (SELECT * FROM PM_RECREATION WHERE PM_NAME = P.PM_NAME)
Nb: The subquery returns rows from PM_RECREATION and here thecorrelation column is PM_NAME. The condition is satisfied if no row exists. PM_NAME STATE_REP DEATH_AGE
Reid G H NSW 73Fisher A QLD 66Cook J NSW 87
SQL 3. 37
- Virtual tables because they look and behave like a base table - but contain no data
Views act as a window through which you can see data that is stored in one or many base tables Consider a base table EMP EMPNO ENAME JOB DEPTNO7369 SMITH MANAGER 207568 JONESANALYST 207788 SCOTT CLERK 207469 ALLEN ANALYST 307521 WARD SALESMAN 30
Views or Virtual Tables
SQL 3. 38
CREATE VIEW EMP20 AS SELECT EMPNO,ENAME,JOB FROM EMP WHERE DEPTNO = 20;VIEW EMP20 EMPNO ENAME JOB7369 SMITH MANAGER7568 JONESANALYST7788 SCOTT CLERK
EMP20 data is stored in the EMP base tableColumns used in views inherit the data type and domain of the base table attributes
An SQL View Statement
SQL 3. 39
Emp (empno,empname, salary_pa, deptno)
Dept (deptno, dname)
CREATE VIEW empdetails (empno, empname, dname, salary_fn) AS
SELECT e.empno, e.empname, d.dname,
e.salary / 26
FROM emp e, dept d
WHERE e.deptno = d.deptno;
A View Involving Two Tables
SQL 3. 40
. Updates via views will be reflected in base tables unless the WITH CHECK OPTION is used when the view is created which prevent inserts and updates from creating rows that the view itself cannot select.UPDATE EMP20SET DEPTNO = 30WHERE EMPNO = 7369- the above query would not be allowed if the WITH CHECK OPTION is used as it would remove the row from the view.
. Views can be used to provide security and to simplify queries.View EMP20 - a user who only has access to this view is not able to look at Employees from other Departments.
The WITH CHECK OPTION
SQL 3. 41
You cannot update a view if the view's defining query contains one of the following constructs:
join
set operator
GROUP BY clause
group function
DISTINCT operator
Restrictions on Updating via Views
SQL 3. 42
. Views do not contain any data of their own or occupy storage space
. Views theoretically can be handled the same as base tables
. View definitions are stored in the Catalog
. A view can be defined on top of another view
. Views are created and dropped using SQL Data Definition statements
. Views can be created using any valid SELECT statement
Notes Concerning Views
SQL 3. 43
Example of NOT EXISTSFrom page 161 of Database Systems by C.J.Date 5th edition
Get Supplier names for suppliers who supply all parts.
SELECT SNAME FROM S
WHERE NOT EXISTS
(SELECT * FROM P
WHERE NOT EXISTS
( SELECT * FROM SP
WHERE S# = S.S# AND P# = P.P# ) );
The query may be paraphrased: “ Select supplier names for suppliers such that there does not exist a part that they do not supply.” Note that this query could not be expressed using the negated form of IN. ( Exercise Why not?)