Sql

39
Syntax to create a Table: CREATE TABLE <table name> ( {<column name> <data type> [(<size>)] [DEFAULT <value>] {[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ] } [ , …] [ , <table level constraints> ] [ … ] ); Example (without Constraints): CREATE TABLE customer ( customer_id NUMBER (4), customer_name VARCHAR2(30), customer_dob DATE, customer_income NUMBER(8,2), customer_type VARCHAR2(15) ); SQL (DDL - Create Table)

description

Use sql

Transcript of Sql

Page 1: Sql

Syntax to create a Table:CREATE TABLE <table name>(

{<column name> <data type> [(<size>)] [DEFAULT <value>] {[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ]}[ , …][ , <table level constraints> ] [ … ]

);

Example (without Constraints):CREATE TABLE customer( customer_id NUMBER (4), customer_name VARCHAR2(30), customer_dob DATE, customer_income NUMBER(8,2), customer_type VARCHAR2(15));

SQL (DDL - Create Table)

Page 2: Sql

Example (with Default Value):CREATE TABLE customer( customer_id NUMBER (4), customer_name VARCHAR2(30), customer_dob DATE, customer_income NUMBER(8,2), customer_type VARCHAR2(15) DEFAULT ‘PERMANENT’);

Example (with Column Constraints):CREATE TABLE customer( customer_id NUMBER (4) CONSTRAINT pk1 PRIMARY KEY, customer_name VARCHAR2(30) CONSTRAINT nn1 NOT NULL, customer_dob DATE, customer_income NUMBER(8,2) CHECK (customer_income >= 0), customer_type VARCHAR2(15) DEFAULT ‘P’

CONSTRAINT type1 CHECK (customer_type IN (‘P’, ‘T’))

CONSTRAINT type2 NOT NULL, customer_PAN VARCHAR2(30) CONSTRAINT PAN1 UNIQUE );

SQL (DDL - Create Table)

Page 3: Sql

Example (with Table Level Constraints):CREATE TABLE customer( customer_id NUMBER (4), customer_name VARCHAR2(30), customer_dob DATE, customer_income NUMBER(8,2), customer_type VARCHAR2(15), customer_PAN VARCHAR2(30), CONSTRAINT pk1 PRIMARY KEY (customer_id, customer_dob), CONSTRAINT uk1 UNIQUE (customer_PAN), CONSTRAINT chk1 CHECK (customer_income >= 0),);

Example (with Column Level FK Constraints):CREATE TABLE sales( sales_id NUMBER (8) PRIMARY KEY, sales_date DATE, sales_type VARCHAR2(15), customer_id NUMBER(4) REFERENCES customer (customer_id));

SQL (DDL - Create Table)

Page 4: Sql

Example (with Table Level FK Constraints):CREATE TABLE sales( sales_id NUMBER (8) PRIMARY KEY, sales_date DATE, sales_type VARCHAR2(15), customer_id NUMBER(4), FOREIGN KEY customer_id REFERENCES customer (customer_id));

SQL (DDL – Create Table)

Page 5: Sql

Syntax to Alter a Table (Adding Columns):ALTER TABLE <table name>ADD(

{<column name> <data type> [(<size>)] [DEFAULT <value>] {[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ]}[ , …][ , <table level constraints> ] [ … ]

);

Example:ALTER TABLE customerADD( customer_phone VARCHAR2(30) NOT NULL, customer_email VARCHAR2(30) UNIQUE);

SQL (DDL – Alter Table)

Page 6: Sql

Syntax to Alter a Table (Modifying Columns):ALTER TABLE <table name>MODIFY(

{<column name> <data type> [(<size>)] [DEFAULT <value>] {[[CONSTRAINT <constraint name>] <constraint definition>]} [ … ]}[ , …]

);

Example:ALTER TABLE customerMODIFY( customer_name VARCHAR2(40) NULL, customer_email VARCHAR2(50));

SQL (DDL – Alter Table)

Page 7: Sql

Syntax to Alter a Table (Dropping Columns):ALTER TABLE <table name>DROP COLUMN <column name>;

Example:ALTER TABLE customer DROP COLUMN customer_email;

SQL (DDL – Alter Table)

Page 8: Sql

Syntax to Alter Table Level Constraints:ALTER TABLE <table name>{ ADD | DROP | ENABLE |DISABLE }[ CONSTRAINT <constraint name> ][ <constraint definition> ];

Example:ALTER TABLE customer ADD CONSTRAINT pk1 PRIMARY KEY (customer_id);

ALTER TABLE customer ADD CONSTRAINT uk1 UNIQUE (customer_PAN);

ALTER TABLE customer ADD CONSTRAINT chk1 CHECK (customer_income >= 0);

ALTER TABLE sales ADD CONSTRAINT fk1 FOREIGN KEY customer_id REFERENCES customer (customer_id);

ALTER TABLE customer DROP CONSTRAINT pk1;

ALTER TABLE customer DISABLE CONSTRAINT uk1;

ALTER TABLE customer ENABLE CONSTRAINT uk1;

SQL (DDL – Alter Table)

Page 9: Sql

Syntax to Drop Table:DROP TABLE <table name> [CASCADE CONSTRAINT];

Example:DROP TABLE customer;

DROP TABLE customer CASCADE CONSTRAINT;

SQL (DDL – Drop Table)

Page 10: Sql

Syntax to Insert Record:INSERT INTO <table name> [(<column list>)]{ VALUES (<value list>) | <query> };

Example:INSERT INTO customer VALUES (1, ‘Mr. Ashok’, ’01-Jan-1970’, 10000, ‘P’);

INSERT INTO customer (customer_id, customer_name) VALUES (1, ‘Mr. Ashok’);

INSERT INTO customer_copy (customer_id, customer_name) SELECT customer_id, customer_name FROM customer;

SQL (DML – Insert)

Page 11: Sql

Syntax to Update Record:UPDATE <table name> SET { <column name> = { <value> | <query> }

[ , … ][ WHERE <filter condition> ];

Example:UPDATE customer SET customer_income = 15000;

UPDATE customer SET customer_income = 15000 WHERE customer_id = 1;

UPDATE customer SET customer_income = customer_income * 1.1, customer_type = ‘P’WHERE customer_id = 1;

UPDATE customer SET customer_income = (SELECT customer_income * 1.1

FROM customer_history WHERE customer_id = 1)

WHERE customer_id = 1;

SQL (DML – Update)

Page 12: Sql

Syntax to Delete Record:DELETE [FROM] <table name> [ WHERE <filter condition> ];

Example:DELETE FROM customer;

DELETE customer;

DELETE FROM customer WHERE customer_id = 1;

SQL (DML – Delete)

Page 13: Sql

Syntax to Select Records:SELECT { * | <column name | expression> [<column alias] }FROM { {<table name> | <query>} [<table alias>] } [ , … ][ WHERE <condition> ][ START WITH <condition CONNECT BY PRIOR <relation> ] [ GROUP BY <column list | expression> [HAVING <group filter condition>] ][ ORDER BY <column list> ];

Example:SELECT * FROM customer;

SELECT customer_id, customer_name FROM customer;

SELECT customer_id ID, customer_name Name FROM customer;

SELECT customer_id, customer_income * 1.1 NewIncome FROM customer;

SELECT * FROM (SELECT customer_id, customer_name FROM customer) Cust;

SQL (DQL – Select)

Page 14: Sql

Row Functions:These functions are grouped into 5 categories.

1. Number FunctionsThese functions receive number values & return number value.

2. Character Functions These receive character or combination of number & character values and return

character or number value.

3. Date FunctionsThese receive date values or combination of date and number values and returnsdate or number value.

4. Conversion FunctionsThese are used to convert data type of the value. Parameters may be number ordate or character and return value will be other than the parameter data type.

5. Other FunctionsThe functions that do not fall in the above types are grouped under this category.

SQL (Row Function)

Page 15: Sql

Number Functions:1. Abs(<val>): Returns positive value.

SELECT abs(-10) FROM dual; -----> 10

2. Mod(<val>,<n>): Returns remainder of division. Value is divided by <n>.SELECT mod(10,3) DROM dual; ------> 1

3. Power(<val>,<n>): Returns value raised up to <n>SELECT power (10,2) FROM dual; ----> 100

4. Sign(<val>): Returns 1 if value is positive, 0 if value is 0 and -1 if value is negative.

SELECT sign(10), sign(0), sign(-10) FROM dual; -------> 1 0 -1

5. Round(<val> [,<n>]): Returns rounded value up to specified <n> decimal digits. If <n> not specified, no decimal digits are included in the output.

SELECT round (10) FROM dual; --------> 10SELECT round (10.4) FROM dual; --------> 10SELECT round (10.5) FROM dual; --------> 11 SELECT round (10.523,2) FROM dual; --------> 10.52SELECT round (10.525,2) FROM dual; --------> 10.53

SQL (Number Function-1)

Page 16: Sql

Number Functions:6. Trunc (<val>[,<n>]): Same as round(), but instead of rounding, it truncates the value up to specified digits.

SELECT trunc (10) FROM dual; ----------> 10 SELECT trunc (10.4) FROM dual; ----------> 10

SELECT trunc (10.5) FROM dual; ----------> 10 SELECT trunc (10.523,2) FROM dual; ----------> 10.52SELECT trunc (10.525,2) FROM dual; ----------> 10.52

7. Ceil (<val>): Returns smallest integer but greater or equal to value. SELECT ceil (10.5) FROM dual; ---------> 11SELECT ceil (-10.5) FROM dual; ---------> -10

8. Floor (<val>): Returns greatest integer but less than or equal to value.SELECT floor (10.5) FTOM dual; ---------> 10SELECT floor (-10.5) FROM dual; ---------> -11

SQL (Number Function-2)

Page 17: Sql

Character Functions:1. Substr (<str>, <start pos> [,<no. of chars>]); Extracts no. of chars. from string starting from starting position. If, no.of chars not specified, it extracts till end of the string.

SELECT substr ('computer',1,3) FROM dual; comSELECT substr ('computer', 4) FROM dual; puterSELECT substr ('computer', -2) FROM dual; erSELECT substr ('computer', -4, 2) FROM dual; ut

2. Length (<str>): Returns length of string in terms of number of characters within the string.

SELECT length (ename) FROM emp;

3. Instr (<str>, <search pattern>): Returns the position of pattern if found within the string. Otherwise returns 0.

SELECT instr (‘Ramesh’, ‘E') FROM dual; 0SELECT instr ('employee', 'e') FROM dual; 1

4. Upper (<str>): Returns the string in upper case characters.SELECT upper ('usha') FROM dual; USHA

SQL (Character Function-1)

Page 18: Sql

Character Functions:5. Lower (<str>): Returns the string in lower case characters.

SELECT lower ('USHA') FROM dual; usha

6. Rpad (<str>,<output size> [,<filler chars>]): Used to pad the filler character within the string during output to the right side of

the string. filler character is used when size is greater than the string lengthSELECT Rpad (‘Ramesh’,10, '*‘ ) FROM dual; Ramesh****

7. Lpad (<str>,<output size> [,<filler chars>]):Same as Rpad but starts padding from left side of the string.

SELECT Rpad (‘Ramesh’,10, '*‘ ) FROM dual; ****Ramesh

8. Rtrim (<str> [,<char set>]):Trims or removes the character set from the right side of the string. If characterset is not defined, then spaces are removed.

SELECT Rtrim (‘Ramesh ‘) FROM emp; RameshSELECT Rtrim (‘Ramesh‘, ‘sh’) FROM emp; Rame

9. Ltrim (<str> [,<char set>]): Same as Rtrim but trims from left side of the string.SELECT Ltrim (‘Ramesh‘, ‘Ra’) FROM emp; mesh

SQL (Character Function-2)

Page 19: Sql

Character Functions:

10. Initcap (<str>): First character of each word will be converted in capital and rest in lower case.

SELECT initcap (‘raj kumar’) FROM dual; Raj Kumar

11. Ascii (<char>): Returns ascii value of given character.SELECT Ascii (‘A’) FROM dual; 65

12. Chr (<ascii value>): Returns the character represented by ascii value.SELECT Chr (65) FROM dual; A

SQL (Character Function-3)

Page 20: Sql

Date Functions:1. Add_Months (<date>, <n>):

Returns a new date by adding or subtracting number of months to or from thegiven date. <n> can be positive (add) or negative (subtract).

SELECT Add_Months (hiredate, 2) FROM emp; SELECT Add_Months (hiredate, -2) FROM emp;

2. Months_Between (<date1>, <date2>):Returns a number indicating the difference between two dates in terms ofmonths. Return value may be positive or negative. Positive if first date is higherthan the second date. Negative if second date is higher.

SELECT Months_Between (sysdate, hiredate) FROM dual; 3. Sysdate: Returns system date.

SELECT sysdate FROM dual;

4. Last_Day (<date>): Returns a new date with last day of the month for the date.SELECT Last_Day (sysdate) FROM dual;

5. Next_Day (<date> , <day name>): Returns a new date for the day mentioned as <day name> which comes after the <date>.

SELECT Next_Day (sysdate, 'SUNDAY') FROM dual;

SQL (Date Function-1)

Page 21: Sql

Cobversion Functions:

1. To_Char (<n/d> [,<output format>]):

Converts number or date value into character as per the output format

mentioned.

SELECT to_char (sysdate, ‘dd/mm/yyyy’) FROM dual;

SELECT to_char (sysdate,'dd-mm-yyyy:hh24:mi:ss') FROM dual;

SELECT to_char (sal,'$9999.99') FROM emp;

SELECT to_char (sal,'$0999.99') from emp;

2. To_Date (<char>, <input format>):

Converts character value in to date as per the given input format.

INSERT INTO emp (empno, hiredate)

VALUES (1, To_Date ('12/04/2001', 'dd/mm/yyyy'));

SQL (Conversion Function-1)

Page 22: Sql

Other Functions:

1. NVL (<val>, <return val if val is null>):

Returns <val> is it is not null else returns the other value.

2. GREATEST (<value list>):

Returns greatest value from the value list of values.

3. LEAST (<value list>):

Returns smallest value from the list of values.

4. USER:

Returns current user name.

SQL (Conversion Function-1)

Page 23: Sql

Other Functions:

DECODE ( <value / expression>{,<search pattern>, <return value>} [,...]

[,<default return value>] )

if <value / expression> matches with any of the search pattern then return value forthe pattern will be returned. If <value /expression> do not match with any pattern thendefault value will be returned. If default return value is not mentioned then null Is thereturn value. For example: Display the grades as defined below:

1 as Poor2 as Average3 as GoodRest as Excellent

SELECT DECODE (grade, 1, ‘Poor’, 2, ‘Average’, 3, ‘Good’, ‘Excellent’) FROM salgrade;

SQL (DECODE Function)

Page 24: Sql

Group Functions:• Group Functions process more than one record at a time and return single value.• Group Functions are only with SELECT and HAVING clauses.• Group Functions output can not be clubbed with individual column output or Row

Functions output without Group By clause.

SUM(<column> | <value> | <expression>)AVG(<column> | <value> | <expression>)MAX(<column> | <value> | <expression>)MIN(<column> | <value> | <expression>)COUNT(* | <column> | <value> | <expression>)

Example:SELECT SUM(sal) FROM emp;SELECT job, SUM(sal) FROM emp GROUP BY job;SELECT COUNT(*), COUNT(comm) FROM emp;

SQL (Group Function)

Page 25: Sql

GROUP BY Clause:Group By clause groups related records based on one or more columns. If GroupFunctions are used with Group By clause, we get the summary output based on oneor more group columns. Whatever individual columns or expressions are used incombination with Summary Function output, they must be defined with Group Byclause.

Group By <Column List>Example:• SELECT job, sum(sal), avg(sal) FROM emp GROUP BY job;• SELECT job, to_char(hiredate, ‘yyyy’), sum(sal), avg(sal)

FROM emp GROUP BY job, to_char(hiredate, ‘yyyy’);

HAVING Clause:This clause is same as WHERE clause but the difference is where clause works onsingle record while having clause works on multiple records. Having Clause isdependent on Group By clause i.e. without using Group By clause, Having Clausecan not be used.

Having <group filter condition>Example:• SELECT job, sum(sal), avg(sal) FROM emp

GROUP BY job HAVING sum(sal) > 3000;

SQL (GROUP BY Clause)

Page 26: Sql

Sub Query:

What is sub-query:It is a method to retrieve data from a table and pass the same to its parent query.At least two queries are must in sub query method. Different queries used in sub-queries are:• Root Query: Top most query is referred as Root Query.• Parent Query: A Query that receives values from other queries.• Child Query / Sub-query: A Query called by another query.

When Sub Query is required:• When output is required from one table and condition(s) require another table. For

example: Display those employees whose department is SALES.SELECT * FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE dname =

‘SALES’)

• When output is required from one or more records and condition requires another record(s) from the same table. For example: Display those employees who are working under KING.

SELECT * FROM emp WHERE mgr = (SELECT empno FROM emp WHERE ename = ‘KING’)

SQL (Sub Query-1)

Page 27: Sql

• When manipulation is required on one table and condition(s) require another table. For example: Delete those employees who are in SALES department.

DELETE FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE dname =

‘SALES’)

Independent or simple Sub-query:An Independent Sub-query is processed once for its parent query. After receivingvalues from Sub-query, Parent Query is processed. In case of Independent Sub-query, Parent Query’s columns are not used.

SELECT * FROM emp WHERE deptno = (SELECT deptno FROM dept WHERE dname =

‘SALES’)

Correlated Sub Query:In correlated Sub Query method, Sub-query is processed for each record of ParentQuery i.e. Sub-query is processed as many times as the number of recordsprocessed by Parent Query.

In case of correlated Sub-query, table aliases are must since the columns fromParent Table and Child Tables are used in a single condition. So to refer the columnsfrom Parent Table into Sub-query, we need to use Table Name or Alias Name withColumns. If Parent and Child both tables are same then Alias is must.

SQL (Sub Query-2)

Page 28: Sql

Process Logic of Correlated Sub-query:Unlike Independent Sub-query, here Parent and Child both tables are processedsimultaneously. Both the tables are opened with the record pointers placed at firstrecords of respective tables. For each movement of record pointer in Parent table,Child table will be processed for all records and values are returned.

In case of correlated Sub-query, there will be minimum two conditions. One conditionthat is to relate Parent and Child table and another condition as filter condition. Forexample:

SELECT E.* FROM emp EWHERE E.sal = (SELECT M.sal FROM emp M WHERE M.empno = E.mgr);

DELETE FROM emp EWHERE E.hiredate > ( SELECT M.hiredate FROM emp M

WHERE M.empno = E.mgr);

SQL (Sub Query-3)

Page 29: Sql

Join Query: Is another method used to relate two or more tables in the form of Parent/Child

relationship.

Only one select statement is required to define multiple tables but all the tables must be related with the help of a condition known as Join Condition.

Generally Number of Join Conditions are “ Number of Tables - 1. If Join Conditions is not defined then output will be Multiple of Records from all the Tables.

Example:SELECT dept.dname, emp.enameFROM dept, empWHERE dept.deptno = emp.deptno;

SELECT emp.ename, salgrade.gradeFROM emp, salgradeWHERE emp.sal BETWEEN salgrade.losal AND salgrade.hisal;

SQL (Join Query-1)

Page 30: Sql

Type of Joins:There are following types of Joins:• Equi Join• Non-equi Join• Self Join• Outer Join

Equi Join:When two tables relation is based on Common Columns / Values (or based onEquality). For example: EMP and DEPT tables are related via DEPTNO commoncolumn (like emp.deptno = dept.deptno).

Non-equi Join:When two tables relation is based on Range of Values (or based on other than Equality). For example: EMP and SALGRADE tables are related via SAL from emptable and LOSAL & HISAL from salgrade table (like emp.sal BETWEENsalgrade.losal AND salgrade.hisal).

SQL (Join Query-2)

Page 31: Sql

Self Join :When a table is related to itself because it keeps data for two entities within it. LikeEMP table keeps Employee and Manager entities. In case of self join table alias aremust since same table is used two or more times. For example:• Display Employee Name & Manager Name for all employees.• Display those employees who joined the company before their Managers

Outer Join:When we need to select Matching Records as well as Non Matching Records fromtwo tables. For Outer Join Query we need to use Outer Join Operator (+). ForExample:• Display all Department names and Employee names including the Department not

having any employee.SELECT D.dname, E.ename FROM emp, deptWHERE emp.deptno (+) = dept.deptno;

• Display all Employees name and Managers name including the Employee nothaving a Manager.

SELECT E.ename, M.ename FROM emp E, emp MWHERE E.mgr (+)= M.empno;

SQL (Join Query-3)

Page 32: Sql

START WITH, CONNECT BY PRIOR Clauses:These clauses are used to get the output in tree walk style. Tree walk style defines

the output in relational hierarchy like: KING |_JONES | |_ AAA | |_ BBB |_BLAKE |_ CCC |_ DDDTree walk style query is possible for those tables that keep two related columns in the

form of parent and child like emp table with empno and mgr columns. Syntax : START WITH <Condition> CONNECT BY PRIOR <parent col> = <child col>;Connect By prior establishes relation between records while start with clause definesthe filter for records selection and it works just like where clause. With tree walkoutput, SQL provides one additional column that keeps the level number of eachrecord as per their relationship in the hierarchy. This column name is LEVEL.It is avirtual column and is not part of any real table, can be used with any table whiledisplaying output in tree walk style. Tree walk hierarchy starts with level no. 1.

SQL (Query – Connect By-1)

Page 33: Sql

Example:1. SELECT ename FROM emp

START WITH mgr IS NULLCONNECT BY PRIOR empno = mgr;

2. SELECT level, ename FROM emp WHERE MOD (level,2) = 0START WITH mgr IS NULLCONNECT BY PRIOR empno = mgr;

3. SELECT LPAD (ename, LENGTH(ename) + level, ‘ ‘) FROM emp WHERE MOD (level,2) = 0START WITH mgr IS NULLCONNECT BY PRIOR empno = mgr;

SQL (Query – Connect BY-2)

Page 34: Sql

Set Operator:These Operators are used to join output of two queries. Number of columns selectedin Query-1and in Query-2 must be same and the data types of respective columnsmust also be same.

<Query-1> <Set Operator> <Query-2>

UNION:Accumulates data from both the Queries and returns All unique values.

SELECT deptno FROM dept UNION SELECT deptno FROM emp;

INTERSECT:Accumulates data from both the Queries and returns Common unique values.

SELECT deptno FROM dept INTERSECT SELECT deptno FROM emp;

MINUS:Returns unique data from first query if they are not available in second query.

SELECT deptno FROM dept MINUS SELECT deptno FROM emp;

UNION ALL:Returns all the data from both the queries including duplicate values. SELECT deptno FROM dept UNION ALL SELECT deptno FROM emp;

SQL (Set Operator)

Page 35: Sql

Data Control Language Commands:Commands under this group are used to grant or revoke privileges on SystemResource or on Objects. There are two commands under this:• GRANT { <system privileges> | <roles> | ALL PRIVILEGES }

TO { <user name> | <role name> | PUBLIC }[ IDENTIFIED BY <password> ][ WITH ADMIN OPTION ];

2. GRANT { <object privileges> | ALL | ALL PRIVILEGES }[ (<column name list>) ]ON <object name>TO { <user name> | <role name> | PUBLIC }[ WITH GRANT OPTION ];

Example:1. GRANT CREATE TABLE, CREATE VIEW TO Scott WITH ADMIN OPTION;2. GRANT ALL PRIVILEGES TO Scott WITH ADMIN OPTION;3. GRANT INSERT, UPDATE (ename,sal) ON emp TO Scott;4. GTANT ALL ON emp TO Scott WITH GRANT OPTION;

SQL ( DCL - 1)

Page 36: Sql

• REVOKE { <system privileges> | <roles> | ALL PRIVILEGES }FROM { <user name> | <role name> | PUBLIC };

2. REVOKE { <object privileges> | ALL | ALL PRIVILEGES }ON <object name>FROM { <user name> | <role name> | PUBLIC };

Example:1. REVOKE CREATE TABLE, CREATE VIEW FROM Scott;2. REVOKE ALL PRIVILEGES FROM Scott;3. REVOKE INSERT, UPDATE (ename,sal) FROM emp TO Scott;4. REVOKE ALL ON emp FROM Scott;

SQL ( DCL - 2)

Page 37: Sql

Transaction Control Language Commands:These commands are to control effects of DML commands on Database. There arefollowing three commands:1. SAVEPOINT <savepoint name>;

Savepoint is a portion within a Transaction to which you may rollback. It allows to rollback portion of current transaction.

2. COMMIT [WORK];To make changes to data permanent.

3. ROLLBACK [ WORK ] [ TO [ SAVEPOINT ] <savepoint> ]; To discard the changes up to specific savepoint or till the last Commit or Rollback

point.Example:SAVEPOINT A;DELETE FROM emp;SAVEPOINT B;DELETE FROM dept;DELETE FROM salgrade;ROLLBACK TO B;COMMIT;

SQL ( TCL - 1)

Page 38: Sql

View:View is like a table but does not keep any data. A view is created on table(s) usingselect statement:

CREATE [ OR REPLACE ] [ FORCE ] VIEW <view name>AS<query> [ WITH READ ONLY ];

Example:1. CREATE VIEW v1 AS SELECT * FROM emp;

1. CREATE FORCE VIEW v2ASSELECT E.empno, E.ename, D.deptno, D.dname, (E.sal + NVL(E.comm,0)) NetFROM emp E, dept DWHERE E.deptno = D.deptno;

3. CREATE VIEW v3ASSELECT v2.ename, v2.dname, S.gradeFROM v2, salgrade SWHERE v2.Net BETWEEN S.losal AND S.hisal;

View

Page 39: Sql

Synonym:It is used to provide another name to objects. So a single object can be accessed bymany different names. It is very useful for Remote Objects to provide them short cutName. It is used for Tables, Views, Synonyms, Sequences, Procedures, etc.Syntax :

CREATE [PUBLIC] SYNONYM <synonym name>FOR [<schema name>.] <object name> [@<dblink name>];

Example:1. CREATE SYNONYM s1 FOR scott.emp;2. CREATE PUBLIC SYNONYM s2 FOR scott.dept;

Sequence:CREATE SEQENCE <sequence name>[ START WITH <n>] - default 1[ INCREMENT BY <n> ] - default 1[ MAXVALUE <n> | NOMAXVALUE ] - default NOMAXVALUE[ MINVALUE <n> | NOMINVALUE ] - default 1[ CYCLE | NOCYCLE ] - default NOCYCLE[ CACHE <n> | NOCHACHE ]; - default 20

Synonym