lecture 2: sql language

36
Oracle Database Administration Lecture 2 SQL language

Upload: databaseguys

Post on 13-Dec-2014

328 views

Category:

Documents


1 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Lecture 2: SQL Language

Oracle Database Administration

Lecture 2

SQL language

Page 2: Lecture 2: SQL Language

Types of SQL statements• DDL (Data Definition Language) : create, drop, alter, for example: CREATE TABLE

• DML (Data Modification Language): select, update, delete, insert

• Transaction control statements: commit, rollback, savepoint

• Session control statements: alter session• System control statements: alter system

Page 3: Lecture 2: SQL Language

DML• SELECT

– query data, – does not modify tables– does not lock (unless FOR UPDATE)– does not wait for any locks

Page 4: Lecture 2: SQL Language

DML• UPDATE

– update data in one table (any number of rows)– locks updated data (until transaction end)– waits for locks if data is locked (can cause

deadlock)– syntax:UPDATE table

SET col1 = value1, col2 = value2

[ WHERE ...]

Page 5: Lecture 2: SQL Language

DML• DELETE

– deletes rows from one table (any number of rows)

– locks deleted data (update will wait)– waits for locks if data is locked (can cause

deadlock)– syntax: DELETE FROM table [ WHERE ... ]

Page 6: Lecture 2: SQL Language

DML• INSERT

– inserts one row or multiple rows – can sometimes wait for a lock

Syntax:INSERT INTO table (col1, col2)

VALUES (val1, val2)or

INSERT INTO table VALUES (val1, val2)or

INSERT INTO table (col1, col2)

SELECT val1, val2 FROM ... (regular select statement)

Page 7: Lecture 2: SQL Language

SELECT• Simple version:

SELECT column_list FROM table

[WHERE condition]

• Table alias:SELECT a.col1, a.col2

FROM table1 a

• Column alias:SELECT table1.col1 [AS] c1,

table1.col2 [AS] c2

FROM table1

Page 8: Lecture 2: SQL Language

SELECT• Select all columns from a table:

SELECT * FROM table1

• When using “*”, no other columns can be specified, the following is illegal:SELECT *, TO_UPPER(name) FROM table1

however, the following is valid: SELECT table1.*, TO_UPPER(name) FROM table1

• Get next sequence value:SELECT my_seq.nextval FROM dual

• Get current sequence value:SELECT my_seq.currval FROM dual

Page 9: Lecture 2: SQL Language

SELECT• With schema (user) name:

SELECT table1.col1, table1.col2

FROM user_name.table1

• Note: user_name cannot be used in column list, the following is illegal:SELECT user_name.table1.col1,

user_name.table1.col2

FROM user_name.table1

• To select data from other user’s table current must have one of the following:• SELECT privilege on the table• SELECT ANY TABLE system privilige

Page 10: Lecture 2: SQL Language

Join select• Join select – select from more than one table• To make a join:

• Explicit syntax: use INNER JOIN keywords• Implicit syntax:

• provide more than one table in FROM clause• provide join condition (in WHERE clause)• Joins without join condition produce Cartesian join (each row from first table is joined with each row from second table):

Page 11: Lecture 2: SQL Language

Joins• Simple explicit join:

SELECT student.id, group.id,

student.name, group.name

FROM student

INNER JOIN group

ON student.group_id = group.id

• Implicit join:SELECT student.id, group.id,

student.name, group.name

FROM student, group

WHERE student.group_id = group.id

Page 12: Lecture 2: SQL Language

Cross join• Explicit notation:

SELECT student.id, group.id,

student.name, group.name

FROM student

CROSS JOIN group

• Implicit notation:SELECT student.id, group.id,

student.name, group.name

FROM student, group

in both cases: number of rows returned = number of students * number of groups

Page 13: Lecture 2: SQL Language

Join select• Any number of tables can appear in SELECT

statement:SELECT student.id, group.id,

course.id, grade.grade

student.name, group.name

FROM student, group, course, grade,

student_courses courses

WHERE student.group_id = group.id

AND courses.student_id = student.id

AND courses.course_id = course.id

AND grade.course_id = course.id

AND student.id = grade.student_id

Page 14: Lecture 2: SQL Language

Joins• Statement:

SELECT student.id, group.id,

student.name, group.name

FROM student, group WHERE

student.group_id = group.id

does not return empty groups.

Page 15: Lecture 2: SQL Language

Outer joins• To return records with no matching join condition use outer join statement:

SELECT student.id, group.id,

student.name, group.name

FROM student

LEFT OUTER JOIN group

ON student.group_id = group.idLeft outer join always returns results from the “left” table (student), even if there are no matching rows in the right table (group)If there is no matching group: group.id IS NULL and group.name IS NULL

Page 16: Lecture 2: SQL Language

Outer joins• RIGHT OUTER JOIN always returns results from the right table even if there are no matching rows in the left table• FULL OUTER JOIN returns results from both tables

Page 17: Lecture 2: SQL Language

Oracle syntax for outer joins• Statement:

SELECT student.id, group.id,

student.name, group.name

FROM student, group WHERE

student.group_id (+) = group.id

returns one record for each student and one record for empty group (student.id and student.name are NULL)

Page 18: Lecture 2: SQL Language

Outer join• (+) operator can be on either side of the = operator:

SELECT student.id, group.id,

student.name, group.name

FROM student, group WHERE

student.group_id = group.id (+)

returns all students including ones with no group• (+) operator cannot be on both sides of the = operator:

WHERE student.group_id (+) = group.id (+)

is illegal

Page 19: Lecture 2: SQL Language

Self join• Table can be joined to itself – self join. • One of the tables must be aliased in the FROM clause:

SELECT dept.id, parent_dept.id,

FROM dept, dept as parent_dept

WHERE dept.parent_id = parent_dept.id

Page 20: Lecture 2: SQL Language

Group functions• Select statement can include group function(s) in the

column clause:SELECT max(salary), min(salary)

FROM employers

WHERE employers.dept = 2

• Select statement with no GROUP BY clause return one record

• Group functions:• count, sum• avg, min, max• stddev, variance (Oracle specific)

Page 21: Lecture 2: SQL Language

Group functions• Statement with group function and no GROUP BY

clause cannot have “regular” columns in SELECT list. The following is illegal:SELECT max(salary), min(salary), name

FROM employers

WHERE employers.dept = 2

Page 22: Lecture 2: SQL Language

Group by clause• Records can be grouped using specified columns:

SELECT max(salary), min(salary), dept

FROM employers

WHERE dept != 2

GROUP BY dept

• Select clause can only include:• group functions• columns from the GROUP BY clause

Page 23: Lecture 2: SQL Language

Having clause• HAVING clause is used with GROUP BY statement• HAVING clause filters records returned after grouping • WHERE clause filters records before grouping

SELECT max(salary), min(salary), dept

FROM employers

WHERE dept != 2

GROUP BY dept

HAVING min(salary) > 100

Page 24: Lecture 2: SQL Language

UNION• UNION, UNION ALL, MINUS, INTERSECT combine

results of two independent SELECT statements• Both statements must return the same number of

columns with the same data types• Column names are taken from the first SELECT

statement• MINUS and INTERSECT statements can be resource

consuming SELECT student.name FROM student

UNION ALL

SELECT teacher.name FROM teacher

Page 25: Lecture 2: SQL Language

ORDER BY• ORDER BY specifies how records are sorted• ORDER BY clause can include:

• column name or column index (1-based)• sort order (ASC or DESC)

SELECT name, salary

FROM employers

ORDER BY salary DESC, 1 ASC

SELECT name as personName, salary

FROM employers

ORDER BY salary DESC, personName ASC

Page 26: Lecture 2: SQL Language

Sub-selectsSELECT name, salary

FROM employers

WHERE salary =

(SELECT MIN(salary)

FROM employers)

• In Oracle sub selects can be used in:• WHERE clause• FROM clause• SELECT clause• ORDER BY clause

Page 27: Lecture 2: SQL Language

Sub-selects• FROM clause sub-selectSELECT COUNT(*) FROM

(SELECT MAX(salary) FROM employers)

• SELECT clauseSELECT ID, (SELECT MAX (salary)

FROM employers

WHERE employers.ID = dept.ID)

FROM dept

Page 28: Lecture 2: SQL Language

Sub-selects• ORDER BY clause sub-selectSELECT ID

FROM dept

ORDER BY (SELECT MAX (salary)

FROM employers

WHERE employers.dept = dept.ID)

Page 29: Lecture 2: SQL Language

WITH clause• WITH clause lets you assign a name to a subquery

block. The query can be then referenced in many places by specifying query name

WITH w AS (

SELECT id

FROM emp

WHERE emp.status = 'ACTIVE')

SELECT * FROM w emp1 WHERE EXISTS

(SELECT * FROM w emp2 WHERE

emp1.id = emp2.boss_id)

Page 30: Lecture 2: SQL Language

Oracle extensions• ROWID pseudo column – unique identifier of a row in

entire database. Will not change when the row is updated

SELECT ROWID, ID FROM student

.......

DELETE FROM student WHERE ROWID = ‘....’

Page 31: Lecture 2: SQL Language

Oracle extensions• ROWNUM pseudo column – numbers rows (starting

from 1) that are returned in a query. • Can be used to limit the number of rows returned:SELECT * FROM student WHERE ROWNUM <= 100

returns at most 100 rowsDELETE FROM student WHERE ROWNUM <= 100

deletes at most 100 rows• ROWNUMs are assigned before the rows are orderedSELECT * FROM student

WHERE ROWNUM <= 100

ORDER BY student.name DESC

Page 32: Lecture 2: SQL Language

Oracle extensions• To get first 100 students in alphabetical order use the

following statement:SELECT *

FROM (SELECT *

FROM students student

ORDER BY NAME DESC)

WHERE ROWNUM <= 100

Page 33: Lecture 2: SQL Language

Oracle extensions• Hierarchical queries: for table that references itself• Special CONNECT BY clauseSELECT *

FROM employers

CONNECT BY boss_id = PRIOR id

START WITH id = 1;

• Selects all employers who’s boss (direct or not) is employer with ID = 1

Page 34: Lecture 2: SQL Language

Hierarchical queries• Special LEVEL pseudo-column is available in hierarchical

queries:SELECT level, e.* FROM employers eCONNECT BY e.boss_id = PRIOR e.idSTART WITH e.id = 1;

Page 35: Lecture 2: SQL Language

Practice SQL statementscreate table employees ( id number, name varchar2(100), boss_id number, dept_id number, salary number );

create table departments ( id number, name varchar2(100)); • Select total number of employees• Select total salary paid to all employees• Select department name, total salary, average salary, number of

employees in each department (including departments with no employees)

• Select employees with highest salary in each department• Select employees that earn more than their direct boss

Page 36: Lecture 2: SQL Language

Practice SQL statements• Select employees that earn more than their direct or indirect

boss• Select department where works the employee with the lowest

salary• Select five employees with the highest salaries• Select employees from 6 - 10 on the salary list (from 6-th to 10-

th best earning person) (!)• Select employers that earn more than average in their

department• Select departments with average salary higher than total average

salary in the company• Select employees that have more than 5 subordinates (direct or

indirect)