Вы находитесь на странице: 1из 53

IF-301 SISTEM BASIS DATA Kuliah 10 Structured Query Language

Institut Teknologi Harapan Bangsa


1

SQL - Structured Query Language


Originally 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 SQL92(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.
2

Structured Query Language

Bahasa merupakan bahasa query deklaratif yang mengindikasikan properti-properti dari data yang hendak diambil. Bahasa yang terstruktur yang digunakan dalam mengelola suatu sistem database: Data Definition Language (DDL): bahasa khusus untuk menspesifikasikan database scheme dengan sekumpulan definisi-definisi tertentu dalam file khusus yang disebut: data dictionary (directory) yang berisi meta data. Metadata adalah data tentang data

Structured Query Language


- Data Manipulation Language (DML): bahasa yang digunakan untuk memanipulasi dan mengakses data yang telah disusun berdasarkan suatu model data tertentu. Manipulasi atau pengaksesan tersebut antara lain adalah:
-

Mengambil informasi dari database (retrieval) Menambah informasi ke dalam database (insertion) Mengurangi informasi dari database (deletion)

Overview of SQL
Data Definition (DDL) CREATE TABLE define table CREATE VIEW define user view of data ALTER TABLE DROP TABLE DROP VIEW add new columns or modify existing columns delete table delete user view
5

Overview of SQL
Data Retrieval (DML) SELECT retrieve data from table

Data Modification (DML)

INSERT UPDATE
DELETE

add a single row or copy rows from other table(s) amend column values
delete rows of data

Overview of SQL
Data Control COMMIT commit changes to the database ROLLBACK rollback previous changes

Data Security
GRANT REVOKE grant access privileges to users revoke access privileges

Data Definition (DDL): Create Table

Creating Tables CREATE TABLE EMP (EMPNO CHAR(6), NAME CHAR(20), SALARY NUMBER(8,0), AGE NUMBER(3,0), DEPTNO CHAR(2));
A table is defined. Space is reserved. The system catalogue is updated. Table and Column Names begin with alpha (A-Z) less than or equal to 30 characters Table names and Column names contain (A-Z,0-9,$,#, __)
8

Data Definition (DDL): Alter Table


This example modifies the BAL column of the ACCOUNTS table so that it has a default value of 0: ALTER TABLE accounts MODIFY (bal DEFAULT 0)

If you subsequently add a new row to the ACCOUNTS table and do not specify a value for the BAL column, the value of the BAL column is automatically 0. The Alter command lets you add a column, add an integrity constraint, redefine a column (datatype, size, default value), enable, disable, or drop an integrity constraint or trigger.
9

The Data Dictionary


- it is a mini-database that stores data that describes the application data held in the database. It is sometimes referred to as the system catalog and the data it stores is also called METADATA (data about data) An example of metadata EMPLOYEE table - Catalog Entries
Object Object Key Name Type Type EMP# attribute PK EMP_AGE attribute DEPT_NO attribute FK Data Nulls Type Allowed Char(9) Int Not Null Char(9) Not Null
10

System Catalogs for Relational Systems


Describe - base-tables - attributes - views - domains - primary-keys - foreign-keys - integrity constraints - security information

The description of the above objects will include owner and creation information and information concerning the above objects that is of use to the DBMS.
11

Zachman framework

Methodologies IE Traditional methodology SDLC


Project ID & selection Project initiation & planning

Database development process

3-schema architecture for database

CASE support for Databases

Upper CASE Lower CASE

Physical Design

Physical database design

Data Process Network People Events Reasons

Impleme ntation

Database implementation

Maintenanc e

Database maintenance

Physical schema

Data Process Network People Events Reasons

Logical Design Design

Logical database design

External schema (user view)

Data Process Network People Events Reasons

Integrated - CASE (I-CASE) 12

Conceptual data modeling (Conceptual schema)

Conceptual (Logical) schema

Data Process Network People Events Reasons

ISA EDM

Enterprise modeling

Example of a Simple SELECT


PART PARTNO P1 P2 P3 PNAME NUT BOLT CARAVAN PRICE $0.20 $1.00 $5000.00 QOH 20 40 3

SELECT pname, price*qoh AS pvalue


FROM PART WHERE price > 0.20 AND price * qoh > 30.0 ORDER BY pname desc;
pname CARAVAN BOLT pvalue $15,000.00 $40.00
13

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
14

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


15

SQL SELECT Statement

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 16

SQL - Sample DB Schema


PRIME _MINISTER

PM_NAME BIRTH_YR YRS_SERVED DEATH_AGE STATE_BORN STATE_REP

MARRIAGE PM_NAME SPOUSE_NAME MAR_YR PM_AGE NR_CHILDREN

MINISTRY

MIN_NR PM_NAME PARTY DAY_COMM MTH_COMM YR_COMM

17

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.

18

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_AGE FROM PRIME_MINISTER WHERE STATE_BORN = NSW ORDER BY BIRTH_YR
PM_NAME Barton E Page E C G Chifley J Holt H E McMahon W Whitlam E G BIRTH_YR 1849 1880 1885 1908 1908 1916 BIRTH_YR + DEATH_AGE 1920 1961 1951 1967 ? ?
19

Using the Logical Operators


Which prime ministers were born in Victoria before the turn of the century?
SELECT PM_NAME, BIRTH_YR, STATE_BORN FROM PRIME_MINISTER WHERE STATE_BORN=VIC AND BIRTH_YR < 1900 PM_NAME Deakin A Bruce S M Scullin J H Menzies R G Curtin J BIRTH_YR 1856 1883 1876 1894 1885 STATE_BORN VIC VIC VIC VIC VIC

20

Combining Logical Operators


Which prime ministers were born in NSW and then represented Victoria or have simply not served less than two years?
SELECT FROM WHERE AND OR PM_NAME, STATE_BORN, STATE_REP, YRS_SERVED PRIME _MINISTER STATE_REP = VIC STATE_BORN = NSW NOT YRS_SERVED < 2 STATE_BORN NSW VIC NSW VIC STATE_REP VIC VIC NSW VIC YRS_SERVED 1.88 3.17 2.92 7.33
21

PM_NAME Holt H E Gorton J G Whitlam E G Fraser J M

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
22

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 MINISTRY WHERE PARTY = Liberal AND YR_COMM BETWEEN 1970 AND 1980

COUNT(*)

COUNT(DISTINCT PM_NAME)

Liberal PMs

23

UNION
PART PARTNO P1 P2 P3 PNAME NUT BOLT CARAVAN PRICE $0.20 $1.00 $5000.00 QOH 21 40 3

SELECT pname, 'q1' AS Query FROM PART WHERE QOH < 22 UNION pname Query SELECT pname, 'q2' AS Query FROM PART NUT q1 CARAVAN q1 WHERE QOH > 20; NUT q2
BOLT q2
24

DELETE

DELETE FROM tablename [t_alias] [ WHERE searchcondition ] Delete one or many rows in a table.

25

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.

26

Set Functions in SELECT


PART PARTNO P1 P2 P3 PNAME NUT BOLT CARAVAN PRICE $1.00 $1.00 $5000.00 QOH 20 20 3

SELECT count(partno) AS Part_count, avg(price) AS Av_price, count(distinct price) AS Price_count FROM part
Part_count 3 Av_price $1667.33 Price_count 2

Set functions supported = avg count max min sum


Set functions may not be used directly in a search condition
27

Use of GROUP BY
List the number of prime ministers from each party. SELECT PARTY, COUNT(*) FROM MINISTRY GROUP BY PARTY
PARTY Country Free Trade Labor Liberal National Labor Nationalist Proctectionist United Australia COUNT(*) 3 1 15 17 1 3 4 5

28

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_MINISTER GROUP BY STATE_BORN, STATE_REP
STATE_BORN ? ? NSW NSW QLD TAS VIC VIC STATE_REP NSW QLD NSW VIC QLD TAS VIC WA COUNT(*) SUM(YRS_SERVED) 4 9.67 1 4.81 5 11.83 1 1.88 2 0.13 1 7.25 7 42.69 1 3.75

29

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_MINISTER WHERE BIRTH_YR > 1900 GROUP BY STATE_BORN
STATE_BORN WA VIC NSW COUNT(*) SUM(YRS_SERVED) 1 ? 2 10.50 3 6.52
30

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_MINISTER GROUP BY STATE_BORN HAVING SUM(YRS_SERVED) < 10
STATE_BORN TAS QLD COUNT(*) SUM(YRS_SERVED) 1 7.25 2 0.13
31

Grouping With the HAVING Clause


PART_SUPPLIER PARTNO SUPPNO P1 S1 P2 S1 P1 S2 P3 S2 QTY_SUPP 20 30 20 10

SELECT partno,Count(suppno) AS Supp_count,Sum(qty_supp ) AS SUPP_COUNT PARTNO Total_qty TOTAL_QTY P1 2 40 FROM part_supplier

32

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 FROM WHERE PM_NAME, DEATH_AGE PRIME_MINISTER DEATH_AGE < (SELECT AVG(DEATH_AGE) FROM PRIME_MINISTER) ORDER BY DEATH AGE

PM_NAME Holt H E Lyons J A Curtin J Deakin A

DEATH_AGE 59 60 60 63
33

Subqueries
Which prime minister died the oldest? Give his name and that age.
SELECT FROM WHERE PM_NAME, DEATH_AGE PRIME_MINISTER DEATH_AGE = (SELECT MAX(DEATH_AGE) FROM PRIME_MINISTER)

PM_NAME Forde F M

DEATH_AGE 93

34

Subquery With IN Operator


List the name and party of each deputy prime minister who was also prime minister. SELECT FROM WHERE DISTINCT DEPUTY_NAME, PARTY DEPUTY_PM DEPUTY_NAME IN (SELECT PM_NAME FROM PRIME_MINISTER)
DEPUTY_NAME Chifley J B Cook J Deakin A PARTY Labor Free Trade Protectionist

35

The ANY Operator


PART_SUPPLIER PARTNO SUPPNO P1 S1 P2 S1 P1 S2 P3 S2 QTY_SUPP 20 30 25 10

SELECT partno, suppno, qty_supp FROM Part_supplier WHERE qty_supp > ANY (SELECT avg(qty_supp) FROM SUPPNO QTY_SUPP S1 30 Part-supplier) S2 25
PARTNO P2 P1
36

Multiple Nested Subqueries


Give the name and birth year of each prime minister who was commisioned after Bob Hawke had turned 21. Order by birth year. SELECT FROM WHERE PM_NAME, BIRTH_YR PRIME_MINISTER 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
37

Subqueries

SELECT 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, create38

Correlated Subqueries
PART_SUPPLIER PARTNO SUPPNO P1 S1 P2 S1 P1 S2 P2 S2 P3 S2 QTY_SUPP 20 30 25 20 10

SELECT partno, suppno, qty_supp FROM Part_supplier PS1 WHERE qty_supp > ANY

(SELECTSUPPNO QTY_SUPP avg(qty_supp) FROM PARTNO P1 S2 25 Part-supplier PS2


P2 S1 30
39

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
40

Which suppliers are supplying more than the average for a part and how much of that part do they supply?

EMP EMPNO E1 E2 E3

Joining Tables
ENAME RED BLUE BROWN MGRNO E1 E1 E1 DEPTNO D1 D1 D2

DEP DEPTNO D1 D2 D3 DNAME TAX PAY LEAVE

SELECT e.empno AS Number, e.ename AS Name, d.dname AS Department FROM emp e, dep d
Number E1 E2 E3 Name RED BLUE BROWN

WHERE e.deptno = d.deptno

Department TAX TAX PAY

41

A Search and Join Condition


For each prime minister born in or after 1900, give his name, birth year and party. SELECT FROM WHERE P.PM_NAME, BIRTH_YR, PARTY PRIME_MINISTER P, MINISTRY M P.PM_NAME = M.PM_NAME AND BIRTH_YR >= 1900
BIRTH_YR 1908 1908 1900 1911 1911 1911 PARTY Liberal Liberal Country Liberal Liberal Liberal
42

PM_NAME Holt H E Holt H E McEwen J Gorton J G Gorton J G Gorton J G

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, PARTY FROM PRIME_MINISTER P,PM_MARRIAGE W,MINISTRY M WHERE P.PM_NAME = W.PM_NAME AND P.PM_NAME = M.PM_NAME AND BIRTH_YR >= 1900
PM_NAME Fraser J M Gorton J G Hawke R J L Holt H E McEwen J McEwen J BIRTH_YR 1930 1911 1929 1908 1900 1900 MAR_YR PARTY 1956 Liberal 1935 Liberal 1956 Labor 1946 Liberal 1921 Country 1968 Country

43

Joining a Table To Itself


EMP EMPNO E1 E2 E3 ENAME RED BLUE BROWN MGRNO E1 E1 E1 DEPTNO D1 D1 D2

SELECT X.empno AS Number, X.ename AS Name, Y.ename AS Manager FROM emp X, emp Y WHERE X.mgrno = Y.empno
Number E1 E2 E3 Name RED BLUE BROWN Manager RED RED RED
44

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_REP FROM PRIME_MINISTER WHERE EXISTS (SELECT * FROM DEPUTY_PM WHERE DEPUTY_NAME = PM_NAME) Nb: The subquery always uses SELECT * and here the correlation column is PM_NAME. The condition is satisfied if at least one row PM_NAME BIRTH_YR STATE_REP exists.
Deakin A Cook J Hughes W M 1856 VIC 1860 NSW 1862 NSW
45

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_AGE FROM PRIME_MINISTER P WHERE NOT EXISTS (SELECT * FROM PM_RECREATION WHERE PM_NAME = P.PM_NAME) Nb: The subquery returns rows from PM_RECREATION and here the correlation column is PM_NAME. The condition is satisfied if no row PM_NAME STATE_REP DEATH_AGE exists.
Reid G H Fisher A Cook J NSW QLD NSW 73 66 87
46

Views or Virtual Tables


- 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 DEPTNO 7369 SMITH MANAGER 20 7568 JONES ANALYST 20 7788 SCOTT CLERK 20 7469 ALLEN ANALYST 30 7521 WARD SALESMAN 30

47

An SQL View Statement


CREATE VIEW EMP20 AS SELECT EMPNO,ENAME,JOB FROM EMP WHERE DEPTNO = 20; VIEW EMP20 EMPNO ENAME JOB 7369 SMITH MANAGER 7568 JONES ANALYST 7788 SCOTT CLERK EMP20 data is stored in the EMP base table Columns used in views inherit the data type and domain of the base table attributes

48

A View Involving Two Tables

Emp (empno,empname, salary_pa, deptno)

Dept (deptno, dname)

CREATE VIEW empdetails (empno, empname, dname, salary_fn) AS

49

The WITH CHECK OPTION


. 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 EMP20 SET DEPTNO = 30 WHERE 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.

50

Restrictions on Updating via Views


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
51

Notes Concerning Views


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

Example of NOT EXISTS

From 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

53

Вам также может понравиться