Structured Query Language(SQL)
Ltitl/Trng/Sql/V1.0
2
SQL
• Non-Procedural Structured Query Language.(4GL)• Data Sub language.• Developed by IBM in the late 1970’s.
• In 1986, the ANSI made SQL as standard for all RDBMS.
• SQL does not support any programming language constructs like if…else OR do…while.
• SQL can be embedded in other programming languages like C, COBOL.
Ltitl/Trng/Sql/V1.0
3
Features of SQL
• SQL is a non-procedural language.
• SQL is used for all types of Database activities by all ranges of users including,
– System administrators.– Database administrators.– Application Programmers– End users.
Ltitl/Trng/Sql/V1.0
4
DBMS LANGUAGES
• Data Definition Language (DDL)– Creating & Altering the structure of the database.
• Data Manipulation Language (DML)– Insert, Update & Delete.
• Data Control Language (DCL)– Controlling access to the database(Grant,Revoke)
Ltitl/Trng/Sql/V1.0
5
•Transaction Control… COMMIT, ROLLBACK •Data Retrieval… SELECT
Ltitl/Trng/Sql/V1.0
6
DATA TYPES SUPPORTED IN SQL
Datatype Description
CHAR(n) To store fixed length string.Maximum length = 255 bytes.
VARCHAR2(n) To store variable length string.Maximum length = 2000 bytes.
LONG(n) To store variable length string.Maximum length = 2 Gigabytes.
NUMBER(p,s) To store numeric dataMax number of significant digits = 38
DATE To store date. (Both date & time are stored)Requires 8 bytes.
RAW(n) To store data in binary format such asSignature, photograpg.Maximum size = 255 bytes.
LONG RAW(n) Same as RAW.Maximum size = 2 Gigabytes.
Ltitl/Trng/Sql/V1.0
7
Tables used :
Emp Dept Salary Desig HistoryEmpcode Deptcode Empcode Desigcode EmpcodeEmpname Deptname Salmonth Designame ChangedateDeptcode Deptmanager Basic DesigcodeBirthdate Deptbudget Allow BasicpayJoindate Deduct GradelvlSexDesigcodeSupcodeGradecodeGradelvlBasicpay
Ltitl/Trng/Sql/V1.0
8
Data Retrieval Using SQL*PLUS
• SQL*PLUS provides a query capability in the form of SELECT statement.
• One can view the current information in the tables by using this statement.
Ltitl/Trng/Sql/V1.0
9
5 parts of basic SQL query•SELECT – list the columns you want
•… (more than one table, use table.field)
•FROM – list of tables used
•WHERE – selection/join criteria (opt)
•GROUP BY – how to summarize (opt)
•ORDER BY – sorting order (opt)
Ltitl/Trng/Sql/V1.0
10
SELECT Command
• Displaying some OR all the columns from a table.
SELECT <col1, col2, … .> OR <*>
FROM <table_name> ;
Ltitl/Trng/Sql/V1.0
11
SELECT * FROM Dept ;
List the Department table.
DEPTCODE DEPTNAME DEPTMANAGER DEPTBUDGETACCT Accounts 7839 19PRCH Purchase 7902 25SALE Sales 7698 39STOR Stores 7521 33FACL Facilities 7233 42PERS Personnel 7233 12
6 rows selected
1.
Ltitl/Trng/Sql/V1.0
12
A Better Way!
2. List the Department table.List the Department table
SELECT Deptcode, Deptname, Deptmanager, Deptbudget FROM Dept ;
DEPTCODE DEPTNAME DEPTMANAGER DEPTBUDGETACCT Accounts 7839 19PRCH Purchase 7902 25SALE Sales 7698 39STOR Stores 7521 33FACL Facilities 7233 42PERS Personnel 7233 12
6 rows selected
Ltitl/Trng/Sql/V1.0
13
Only Some Columns
SELECT Deptmanager, Deptname FROM Dept ;
3. List all department managers with the names of their department
DEPTMANAGER DEPTNAME7839 Accounts7902 Purchase7698 Sales7521 Stores7233 Facilities7233 Personnel
6 rows selected
Ltitl/Trng/Sql/V1.0
14
WHERE Predicate ( = )
SELECT Empname, Deptcode
FROM Emp
WHERE Deptcode = ‘Acct’ ;
4. List all employees of the Accounts department.
EMPNAME DEPTCODE
Reddy ACCT
Menon ACCT
Kaul ACCT
Ltitl/Trng/Sql/V1.0
15
WHERE Predicate ( < )
SELECT Empname, Gradecode
FROM Emp
WHERE Gradecode < 10 ;
5. List all officers.
EMPNAME GRADECODE
Naik 4Reddy 1
Murthy 4Wilson 4Jain 4Menon 4Khan 6Kumaran 4Kamal 4
9 rows selected
Ltitl/Trng/Sql/V1.0
16
Date Comparison
SELECT Empname, Birthdate
FROM Emp
WHERE Birthdate > ‘01-Jan-70’ ;
6. List all young employees.
EMPNAME BIRTHDATE
Shah 12-Aug-76Roy 01-Jul-72
Gupta 26-Jul-73Singh 20-Jan-74Patil 30-Apr-75Shroff 14-Nov-77Kaul 26-May-75Uma 14-Jan-75
8 rows selected
Ltitl/Trng/Sql/V1.0
17
e.g.
SELECT DISTINCT deptcode FROM emp ;
DISTINCT is an argument that provides a way for you to eliminate duplicate values.
Eliminating Redundant Data
Ltitl/Trng/Sql/V1.0
18
Use of Boolean operators
1. SELECT * FROM emp
WHERE Basicpay >= 2500 AND Basicpay <= 4500 ;
2. SELECT * FROM emp
WHERE Desigcode = ‘Engg’ OR Basicpay > 3000 ;
3. SELECT empname FROM emp
WHERE NOT deptcode = ‘Acct’ ;
Ltitl/Trng/Sql/V1.0
19
In Operator
1. SELECT empname FROM emp
WHERE deptcode IN(‘Acct’, ‘Pers’) ;
2. SELECT empname FROM emp
WHERE deptcode NOT IN(‘Acct’, ‘Pers’) ;
IN operator can be used to select rows that match one of the values included in the list.
Ltitl/Trng/Sql/V1.0
20
Between construct
Defines a range that values must fall into make the predicate true.
List all middle level staffList all middle level staff
SELECT Empname, GradecodeFROM EmpWHERE Gradecode BETWEEN 10 AND 15;
EMPNAME GRADECODE
Roy 12Gupta 12
Singh 12Uma 15
Ltitl/Trng/Sql/V1.0
21
Like construct
Used for pattern searching. Pattern consists of characters to be matched & the wildcard’ characters.
WildCard chars. Matches_ (under score) Any single character.% Any sequence of zero or
more characters.
Ltitl/Trng/Sql/V1.0
22
Like construct
List all employees with UMA in their names
SELECT EmpnameFROM EmpWHERE Upper(Empname) LIKE ‘%UMA%’ ;
EMPNAMEKumaranUma
Ltitl/Trng/Sql/V1.0
23
Null values
List the employees who have not been assigned to any supervisor
SELECT Empname, SupcodeFROM EmpWHERE Supcode IS NULL ;
EMPNAME SUPCODE
Reddy
Ltitl/Trng/Sql/V1.0
24
Compound Predicate - Interval
SELECT Empname, Sex, Joindate
FROM Emp
WHERE Sex = “F”
AND Joindate BETWEEN(sysdate - 5*365)
AND (sysdate - 6*365) ;
List the female employees who have just completed 5 years
EMPNAME SEX JOINDATE
Uma F 22-Oct-91
Ltitl/Trng/Sql/V1.0
25
Predicate using OR
SELECT EmpName
FROM Emp
WHERE BirthDate < (sysdate - 50*365)
OR JoinDate < (sysdate - 20*365) ;
List employees who are either 50 years or more or have morethan 20 years experience.
EMPNAME
ReddyKumaranKamal
Ltitl/Trng/Sql/V1.0
26
Parentheses in Predicate
SELECT EmpName
FROM Emp
WHERE DesigCode = ‘FRMN’
AND ((BirthDate < (sysdate - 50*365)
OR JoinDate < (sysdate - 20*365));
List foremen who are either 50 years or more or have more than20 years experience.
EMPNAME
KumaranKamal
Ltitl/Trng/Sql/V1.0
27
Expressions in SELECT List
SELECT Empcode, (Basic + Allow -Deduct ) * 0.01
FROM Salary
WHERE SalMonth = ‘1-Mar-97’;
List 1% of take-home pay of all employees.
Ltitl/Trng/Sql/V1.0
28
EMPCODE (BASIC+ALLOW-DEDUCT) * 0.01
-------------- --------------------------------------------
7129 440
7233 440
7345 143
7369 66
7844 198
7876 44
7900 55
7902 330
7934 77
17 rows selected.
Ltitl/Trng/Sql/V1.0
29
Aliasing
SELECT EmpName,
TRUNC(SYSDATE - BirthDate) / 365) AGE
FROM Emp ;
List the present age of all the employees.
Ltitl/Trng/Sql/V1.0
30
EMPNAME AGE
Shah 20Naik 36Reddy 54Murthy 34Roy 24Shroff 19Kaul 21Kumaran 57Kamal 46Uma 22
17 rows selected.
Ltitl/Trng/Sql/V1.0
31
Order By
• For getting the resultant rows in a specified order.
• Ascending order is default.
List all employees ordered by age
SELECT EmpName, TRUNC(SYSDATE - BirthDate)/365 AGEFROM EmpORDER BY BirthDate ;
Ltitl/Trng/Sql/V1.0
32
EMPNAME AGE
Kumaran 57Reddy 54Kamal 46Menon 38Uma 22Patil 21Kaul 21Shah 20Shroff 19
9 rows selected
Ltitl/Trng/Sql/V1.0
33
Sorting Ascending / Descending
SELECT EmpName, GradeCode, GradeLevelFROM EmpWHERE GradeCode BETWEEN 10 AND 25ORDER BY GradeCode, GradeLevel DESC ;
List middle level staff according to seniorityList middle level staff according to seniority
Ltitl/Trng/Sql/V1.0
34
EMPNAME GRADECODE GRADELEVEL
Gupta 12 3Roy 12 2Singh 12 1Uma 15 3Patil 20 4Shroff 20 3Shah 20 2Kaul 20 1
8 rows selected
Ltitl/Trng/Sql/V1.0
35
Sorting by Result of Expression
SELECT EmpName, TRUNC(SYSDATE - BirthDate/365) AGE, GradeCode, GradeLevel
FROM EmpORDER BY 2 DESC, GradeCode, GradeLevel DESC ;
List middle level staff according to seniorityList all according to age and seniority
Ltitl/Trng/Sql/V1.0
36
EMPNAME AGE GRADECODE GRADELEVEL
Kumaran 57 4 1reddy 54 1 1Kamal 46 4 1Menon 38 4 1Wilson 37 4 4Patil 21 20 4Kaul 21 20 1Shah 20 20 2Shroff 19 20 3
9 rows selected.
Ltitl/Trng/Sql/V1.0
37
• Act on a group or set of rows and return one row of summary information per set.
SUM Computes the total value of the group. AVG Computes the average value of the group. MIN Computes the minimum value of the group. MAX Computes the maximum value of the group COUNT Counts the no. of NON-NULL values for
the specified group. COUNT(*) Counts the no. of rows including those
having NULLvalues for the given condition.
AGGREGATE Functions
Ltitl/Trng/Sql/V1.0
38
AGGREGATE Functions
SELECT COUNT(*)
FROM Emp
WHERE Supcode = ‘7844’ ;
Count employees reporting to Singh.
Count(*)
1
Ltitl/Trng/Sql/V1.0
39
• The grouping of rows is achieved by using the GROUP BY clause.
• Allows you to define a subset of the values in a particular field in terms of another field, and apply an aggregate functions to the subset.
• Enables you to combine fields and aggregate functions in a single SELECT statement
GROUP BY - Aggregate Functions
Ltitl/Trng/Sql/V1.0
40
SELECT Supcode, COUNT(*)
FROM Emp
GROUP BY Supcode
ORDER BY Supcode ;
GROUP BY - Aggregate Functions
List the number of staff reporting to each supervisor.
SUPCODE COUNT(*)
7566 17698 57782 17788 17839 67844 17902 1
1
8 rows selected.
Ltitl/Trng/Sql/V1.0
41
SELECT EmpCode,
SUM(Basic + Allow - Deduct) PAY
FROM Salary
WHERE SalMonth BETWEEN ‘1-Apr-96’
AND ‘31-Mar-97’
GROUP BY EmpCode
ORDER BY EmpCode ;
GROUP BY - Sum
List the total take-home pay during 96-97 for all employees.
Ltitl/Trng/Sql/V1.0
42
EMPCODE PAY
7129 1320007233 1320007345 429007369 198007499 561007876 132007900 165007902 990007934 15400
17 rows selected.
Ltitl/Trng/Sql/V1.0
43
SELECT GradeCode, MAX(Basic), MIN(Basic)
FROM Grade
GROUP BY GradeCode
ORDER BY GradeCode ;
GROUP BY - Max & Min
List the maximum & minimum salaries in grades.
Ltitl/Trng/Sql/V1.0
44
GRADECODE MAX(BASIC) MIN(BASIC)
1 25000 250004 21000 150006 13000 1100012 9000 800015 7000 600020 3500 2000
6 rows selected.
Ltitl/Trng/Sql/V1.0
45
• Defines criteria used to eliminate certain groups from the output, just as the WHERE clause does for individual rows.
• HAVING can take only arguments that have a single value
per output group.
HAVING
Ltitl/Trng/Sql/V1.0
46
SELECT SupCode, COUNT(*)
FROM Emp
GROUP BY SupCode
HAVING COUNT(*) > 3
ORDER BY SupCode ;
HAVING
List the number of staff reporting to each supervisorhaving more than 3 people working under them.
SUPCODE COUNT(*)7698 57839 6
Ltitl/Trng/Sql/V1.0
47
SELECT EmpCode, SUM(Basic + Allow - Deduct) PAY
FROM Salary
WHERE SalMonth BETWEEN ‘1-Apr-96’ AND ‘31-Mar-97’
GROUP BY EmpCode
HAVING SUM(Basic + Allow - Deduct)
ORDER BY EmpCode ;
Where - Group By - Having
List the total take-home pay during 96-97 for allemployees getting a total take-home-pay < Rs. 20000
EMPCODE PAY
7369 198007876 132007900 165007934 15400
Ltitl/Trng/Sql/V1.0
48
SELECT GradeCode, MAX(Basic), MIN(Basic)
FROM Grade
GROUP BY GradeCode
HAVING MIN(Basic) < 4000
ORDER BY GradeCode ;
Where - Group By - Having
List the maximum and minimum basic salary in each grade for grades with start < Rs. 4000
GRADECODE MAX(BASIC) MIN(BASIC)
20 3500 2000
Ltitl/Trng/Sql/V1.0
49
• The process of forming rows from two or more tables by comparing the contents of related cloumns is called ‘Joining Tables’.
• Joins are the foundation of multi-table query processing in SQL.
Syntax :
SELECT <col1,col2,...>
FROM <table_name>
WHERE <logical expr.> ;
Joining Table
Ltitl/Trng/Sql/V1.0
50
• Equi-Join
• Cartesian Join
• Self Join
• Outer Join
Joining Table - Types of Joins
Ltitl/Trng/Sql/V1.0
51
SELECT EmpCode, EmpName, Grade.Basic,Emp.Basic
FROM EMP, GRADE
WHERE Emp.GradeCode = Grade.GradeCode
AND Emp.GradeLevel = Grade.GradeLevel ;
Natural Join - Equi-Join
Check the basic salary of all employees.
Ltitl/Trng/Sql/V1.0
52
SELECT E.Empname, S.EmpName Supervisor,
FROM EMP E, EMP S
WHERE E.SupCode = S.EmpCode ;
Self Join
• Match and retrieve rows that have a matching value in different cloumns of the same table.
List employees along with the names of their supervisors
Ltitl/Trng/Sql/V1.0
53
• A cartesian product matches every row of one table to every row of the other table.
e.g.
SELECT EmpName, DeptName
FROM EMP, DEPT
WHERE DesigCode = ‘clerk’ ;
Cartesian Join
Ltitl/Trng/Sql/V1.0
54
• Retrieving selected rows from one table that don’t match rows in the other table.
Outer Join
To find department names & the employees in them, as well as those departments which do not have employees in them
SELECT DeptName, EmpName FROM EMP, DEPT WHERE EMP.DeptCode(+) = DEPT.DeptCode ;
Ltitl/Trng/Sql/V1.0
55
SELECT SupCode, COUNT(*)
FROM EMP
WHERE GradeCode < 10
GROUP BY SupCode
HAVING COUNT(*) > 3 ;
List the number of officers reporting to each supervisorshaving more than 3 people working under them.
Ltitl/Trng/Sql/V1.0
56
Nested Queries ( Subquery )
• Placing a query inside the predicate of another query, and using the inner query’s output in the predicate’s true or false
condition.
Subqueries divided into two groups.1. Single-Row Subquery
– Returns only one value to the outer query.
2. Multi-Row Subquery– Returns multiple values to the outer query
Ltitl/Trng/Sql/V1.0
57
Single-Row Subquery
SELECT EmpName FROM EMP
WHERE DesigCode = (SELECT DesigCode FROM EMP
WHERE EmpName = ‘scott’) ;
To find out all the employees who have the same job as ‘scott’.
Ltitl/Trng/Sql/V1.0
58
Single-Row Subquery
SELECT EmpName
FROM EMP
WHERE DeptCode = (SELECT DeptCode
FROM DEPT
WHERE DeptName = ‘sales’);
To list the names of all employees working in sales dept; assuming that dept no. of sales dept is not known.
Ltitl/Trng/Sql/V1.0
59
Multi-Row Subquery
SELECT EmpName, DesigCode, Salary
FROM EMP
WHERE DeptCode = 20 AND
DesigCode IN (SELECT DesigCode FROM EMP
WHERE DeptCode = 30) ;
List the name, job and salary of people in dept 20 who have the same job as people in dept. 30.
Ltitl/Trng/Sql/V1.0
60
Multiple levels of Nesting
SELECT EmpName, DesigCode, Salary
FROM EMP WHERE DeptCode = 20
AND DesigCode IN (SELECT DesigCode FROM EMP
WHERE DeptCode = (SELECT DeptCode
FROM DEPT WHERE DeptName = ‘sales’) ;
Find name, job and salary of people in dept 20 who have the same job as people in the sales dept.
Ltitl/Trng/Sql/V1.0
61
Subqueries returning Multiple values
SELECT DeptCode, EmpName, Salary
FROM EMP
WHERE (DeptCode, Salary)
IN (SELECT DeptCode, MAX(Salary)
FROM EMP
GROUP BY DeptCode) ;
Find out who are the highest paid employees in each dept.
Ltitl/Trng/Sql/V1.0
62
EXISTS Operator
Used to base a predicate on whether a subquery produces output or not.
EXISTS is an operator that produces a True or False value.
It takes a subquery as an argument and evaluates to True if
it produces any output or false if it does not.
Ltitl/Trng/Sql/V1.0
63
e.g. To list data from customer table if and only if
one or more of the customers in the customers
table are located in ‘San Jose’.
Select cnum, cname, city From customer
Where Exists
(Select * From customer
Where city = ‘San Jose’) ;
Ltitl/Trng/Sql/V1.0
64
EXISTS Operator
To list all department details from Dept. table which has atleast one employee.
SELECT * FROM DEPT AWHERE EXISTS (SELECT * FROM EMP B
WHERE B.DeptCode = A.DeptCode) ;
Ltitl/Trng/Sql/V1.0
65
•insert into tablename [(col1, col2, …)]
values (exp1, exp2, …);
•If the col names are not listed, the data is assigned to all cols in order
•To insert only into certain cols, name them
… cols not named are given null values
Inserting rows of data
Ltitl/Trng/Sql/V1.0
66
INSERT one complete row
INSERT INTO HISTORY
VALUES
(‘7369’, ‘01-Aug-96’, ‘SLMN’, ‘12’, 5000) ;
Ltitl/Trng/Sql/V1.0
67
INSERT one partial row
INSERT INTO EMP
(EmpCode, EmpName, Basic)
VALUES
(‘9123’, ‘Hussein’, 250) ;
Employ Hussein as a temporary employee.
Ltitl/Trng/Sql/V1.0
68
INSERT thru Subquery
INSERT INTO SALARY
SELECT EmpCode, trunc(Sysdate, mon), Basic,
Basic*1.5, Basic*0.3
FROM EMP ;
Update the SALARY table for the month.
Ltitl/Trng/Sql/V1.0
69
Delete one row
DELETE FROM EMP
WHERE EmpCode = ‘7934’ ;
Delete employee record of Kaul.
Ltitl/Trng/Sql/V1.0
70
Bulk Delete
DELETE FROM EMP
WHERE DeptCode = ‘FLNG’ ;
Delete all employee records of Filing Department.
Ltitl/Trng/Sql/V1.0
71
Delete entire Table
DELETE FROM SALARY ;
Delete the entire SALARY Table.
Ltitl/Trng/Sql/V1.0
72
Update one Row
UPDTAE EMP
SET GradeCode = ‘4’,
DesigCode = ‘MNGR’,
Basic = 15000
WHERE EmpCode = ‘7654’ ;
Promote Gupta as Manager (Exports)
Ltitl/Trng/Sql/V1.0
73
Bulk Update
UPDTAE DEPT
SET DeptBudget = DeptBudget * 1.25
WHERE DeptCode != ‘FACL’ ;
Raise the budget by 25% for all the departments except Facilities department.
Ltitl/Trng/Sql/V1.0
74
Creating a table with SQL
• CREATE TABLE tablename
(colname datatype [default value] [colconstrt]
… tblconstraint, …, tblconstraint)
[TABLESPACE tablespacename];
• Only one primary key per table (mult cols OK)
Ltitl/Trng/Sql/V1.0
75
• default 50 – use 50 if no value is given
• Column constraints:
•…not null (default is to allow nulls)
•…check condition
•…unique
•…primary key
•…references tblname [colname]
Constraint examples
Ltitl/Trng/Sql/V1.0
76
•(p is precision, s is scale)
•VARCHAR2(p) – variable length string
…… p can be 1 to 4000
•NUMBER(p,s) - p is # of digits
…… s is # of decimal digits (like Fortran)
•DATE - + time, many possible formats
… from 1/1/4712 BC to 12/31/4712 AD
Common datatypes
Ltitl/Trng/Sql/V1.0
77
•CHAR(p) – older fixed length format
… p from 1 to 255, pads with blanks
•LONG – variable length text string to 2G
… use is limited in queries
• LOB – replacing LONG, up to 4G (video)
•…”Large Object Block”
Ltitl/Trng/Sql/V1.0
78
DDL for Table Dept
Create table dept
( Deptcode char(4) constraint dept_pk primary key,
Deptname char(25) not null,
Deptmanager char(6),
Deptbudget number not null );
Ltitl/Trng/Sql/V1.0
79
DDL for Table Emp
Create table emp
( Empcode char(6) constraint emp_pk primary key,
Empname char(20) not null,
Deptcode char(4) constraint emp_dept_rc references
dept(deptcode) ,
Birthdate date not null,
Joindate date not null,
Sex char(1) not null
check(sex in(‘M’, ‘F’)),
Desigcode char(4) not null
constraint emp_desig_rc references desig(desigcode)
Ltitl/Trng/Sql/V1.0
80
Supcode char(6)constraint emp_sup_rc references emp(empcode),
Gradecode number(2),
Basic number(5)) ;
Contd...
Ltitl/Trng/Sql/V1.0
81
DDL for Table Grade
Create table grade
( Gradecode number(2) not null,
Gradelevel number not null,
Basic number(5) not null,
constraint grade_pk primary key(Gradecode, Gradelevel) ;
Ltitl/Trng/Sql/V1.0
82
•DROP TABLE tablename
… (ROLLBACK cannot restore this)
•DROP removes the table definition
•DELETE just removes the rows
it leaves the table
To remove a table
Ltitl/Trng/Sql/V1.0
83
Alter table
• Best to get your tables correct the first time
• But if alteration is needed, you can:
•… add a new column
•… change a column’s definition
Ltitl/Trng/Sql/V1.0
84
Example adding new columns
• alter table customers add (fax char(12),
ctype char(1) check(ctype in (‘I’,’B’)));
• Cannot add a new column as not null
… it starts out all null (empty)!
Ltitl/Trng/Sql/V1.0
85
Example modifying a column
• Alter table customers modify ( street varchar2(50));
• Can increase (not decrease) width
• Restrictions also exist on changes to:
•… datatypes and constraints (cur violated)
Ltitl/Trng/Sql/V1.0
86
Views - Creation
View is a logical table based on one or more tables.
View can be used as if it is a table.
View does not contain data of their own.
Whenever a view is accessed, the query is evaluated. Thus view is dynamic.
Any changes made in the view affect the tables on which the view is based.
View helps to hide the ownership details of a table and complexity of query used to retrieve data, from the user.
Ltitl/Trng/Sql/V1.0
87
Views - Creation
Create a view for Employee-Age.
CREATE VIEW EMPAGE (EmpCode, Age) AS(SELECT EmpCode, TRUNC((SYSDATE - BirthDate)/365)FROM EMP) ;
Ltitl/Trng/Sql/V1.0
88
Views - Creation
Create a view for Employee-Pay.
CREATE VIEW EMPPAY (EmpCode, NetPay, SalMonth) AS(SELECT EmpCode, (Basic + Allow - Deduct), SalMonthFROM SALARY) ;
Ltitl/Trng/Sql/V1.0
89
Use of Views
List employees who are older than their supervisors.
SELECT E.EmpCode, EmpName
FROM EMP E, EMPAGE A
WHERE E.EmpCode = A.EmpCode
AND age > (SELECT Age FROM EMPAGE
WHERE E.SupCode = EmpCode ) ;
Ltitl/Trng/Sql/V1.0
90
Commit
• Makes permanent all changes made since last Commit or since the beginning of the user’s session.
Syntax :
COMMIT [work] ;
work - is optional & only provided for readability.
Ltitl/Trng/Sql/V1.0
91
RollBack
• RollBack undoes all the changes that has been done since the last commit or last Rollback or the named savepoint.
Syntax :
ROLLBACK [work] ;
ROLLBACK TO Savepoint <savepoint_name> ;
Ltitl/Trng/Sql/V1.0
92
Savepoint
Savepoint <savepoint_name> ;
Savepoint helps in breaking a transaction into parts.
Useful if only a part of changes made are to be discarded.
If the name of an existing savepoint is reused, the old savepoint is erased.
Commit or Rollback without any parameters will erase all savepoints.
Rollback To Savepoint will undo all changes made after the Savepoint.