charutar vidya mandal’s semcom vallabh … unit-4.pdfa correlated subquery is evaluated once for...

22
US03CBCA01 (Relational Database Management Systems - I) Unit - IV Page 1 of 22 CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh Vidyanagar Faculty Name: Ami D. Trivedi Class: SYBCA (SEM-III) Subject: US03CBCA01 (Relational Database Management Systems-I) *UNIT 4 (QUERY, SUBQUERY, JOINS, TRANSACTION MANAGEMENT AND REPORTING THROUGH SQL*PLUS) GROUP BY Clause GROUP BY clause is another section of the select statement. This optional clause tells Oracle to group rows based on distinct values that exist for specified columns. GROUP BY clause creates a data set, containing several sets of records grouped together based on a condition. A query containing a group by clause is processed in the following way: 1. Select all rows that satisfy the condition specified in the where clause. 2. From these rows form groups according to the group by clause. 3. Discard all groups that do not satisfy the condition in the having clause. 4. Apply aggregate functions to each group. 5. Retrieve values for the columns and aggregations listed in the select clause. SYNTAX SELECT <ColumnName1>, <ColumnName2>, <ColumnNameN>, AGGREGATE_FUNCTION (<Expression>) FROM TableName WHERE <condition> GROUP BY <ColumnName1>, <ColumnName2>, <ColumnNameN>; EXAMPLE SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO; HAVING Clause HAVING clause can be used in conjunction with the GROUP BY clause. HAVING imposes a condition on the GROUP BY clause, which further filters the groups created by the GROUP BY clause. Each column specification specified in the HAVING clause must occur within a statistical function or must occur in the list of columns named in the GROUP BY clause.

Upload: trinhlien

Post on 22-May-2018

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 1 of 22

CHARUTAR VIDYA MANDAL’S SEMCOM

Vallabh Vidyanagar

Faculty Name: Ami D. Trivedi Class: SYBCA (SEM-III) Subject: US03CBCA01 (Relational Database Management Systems-I) *UNIT – 4 (QUERY, SUBQUERY, JOINS, TRANSACTION MANAGEMENT AND REPORTING THROUGH SQL*PLUS) GROUP BY Clause

GROUP BY clause is another section of the select statement. This optional clause tells Oracle to group rows based on distinct values that exist for specified columns. GROUP BY clause creates a data set, containing several sets of records grouped together based on a condition. A query containing a group by clause is processed in the following way: 1. Select all rows that satisfy the condition specified in the where clause.

2. From these rows form groups according to the group by clause.

3. Discard all groups that do not satisfy the condition in the having clause.

4. Apply aggregate functions to each group.

5. Retrieve values for the columns and aggregations listed in the select clause.

SYNTAX

SELECT <ColumnName1>, <ColumnName2>, <ColumnNameN>, AGGREGATE_FUNCTION (<Expression>) FROM TableName WHERE <condition> GROUP BY <ColumnName1>, <ColumnName2>, <ColumnNameN>; EXAMPLE SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO;

HAVING Clause HAVING clause can be used in conjunction with the GROUP BY clause. HAVING imposes a condition on the GROUP BY clause, which further filters the groups created by the GROUP BY clause. Each column specification specified in the HAVING clause must occur within a statistical function or must occur in the list of columns named in the GROUP BY clause.

Page 2: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 2 of 22

SYNTAX SELECT <ColumnName1>, <ColumnName2>, <ColumnNameN>, AGGREGATE_FUNCTION (<Expression>) FROM TableName WHERE <condition> GROUP BY <ColumnName1>, <ColumnName2>, <ColumnNameN> HAVING AGGREGATE_FUNCTION (<Expression>) <operator> <value>; EXAMPLE SELECT DEPTNO, COUNT(EMPNO) FROM EMP GROUP BY DEPTO HAVING COUNT(EMPNO) > 2; Rules for Group By and having Clause

Columns listed in the select statement have to be listed in the GROUP BY clause

Columns listed in the GROUP BY clause need not be listed in the SELECT statement.

Only group functions can be used in the HAVING clause.

The group functions listed in the having clause need not be listed in the SELECT statement.

*SUBQUERY A sub query is a query within a query. A subquery is a form of an SQL statement that appears inside another SQL statement. Inner query executes first then the outer query executes. Most often, the subquery will be found in the WHERE clause. A query can be used in a condition of a where clause. In such a case the query is called a sub query and the complete select statement is called a nested query. Main / Outer query is called Parent query. Sub / Inner query is called Child query. The parent query uses the rows returned by the child query i.e. subquery. Subquery can be used to:

1. Insert records in target table 2. Create tables and insert records in created tables 3. Update records in target table 4. Create views 5. Provide values for conditions in WHERE, HAVING, IN and so on used with

SELECT, UPDATE and DELETE statement

SIMPLE ORACLE SUBQUERY A simple subquery is evaluated once for each table. Single-Row Operator (>,=,<=,>=,<>, !=) – subquery must return only one value. Multiple Row Operators (IN, ANY, ALL) – subquery can return more than one value

Page 3: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 3 of 22

WHERE clause A respective condition in the where clause then can have one of the following forms: 1. Set-valued subqueries SYNTAX < expression > [ not ] in ( < subquery > )

< expression > < comparison operator > [ any | all ] ( < subquery > ) An <expression> can either be a column or a computed value. For example - to select all employees whose department is located in Chicago.

SELECT EMPNO, ENAME, JOB, SAL, DEPTNO FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM DEPT WHERE LOC = 'CHICAGO');

The sub query retrieves only one value (the number of the department located in Boston). Thus it is possible to use “=” instead of in.

As long as the result of a subquery is not known in advance, i.e., whether it is a single value or a set, it is advisable to use the in operator.

Conditions of the form <expression> <comparison operator> [any | all] <subquery> are used to compare a given <expression> with each value selected by <subquery>.

Clause ANY and ALL are used with any relational operator except =.

ANY means any one of the value in the set. ANY clause is equivalent to using MIN() on subquery with < relational operator.

Condition evaluates to true if there exists at least on row selected by the subquery for which the comparison holds.

If the subquery produces an empty result set, the condition is not satisfied.

ALL means all the value in the set. ALL clause is equivalent to using MAX() on subquery with > relational operator.

Condition evaluates to true if for all rows selected by the subquery the comparison holds.

In this case the condition evaluates to true if the subquery does not produce any row or value.

Example: Retrieve all employees who are working in department 10 and who earn at least as much as any (i.e., at least one) employee working in department 30: SELECT * FROM EMP WHERE SAL >= ANY (SELECT SAL FROM EMP WHERE DEPTNO = 30) AND DEPTNO = 10; Note: ANY and SOME operators are equivalent to the OR operator and the IN operator.

Page 4: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 4 of 22

2. Test for (non)existence

SYNTAX [not] exists (<subquery>)

Often a query result depends on whether certain rows do (not) exist in (other) tables. Such type of queries is formulated using EXISTS operator. EXISTS operator is used with correlated subqueries.

This operator is used to test whether a value retrieved by the outer query exists in the result set of the values retrieved by the inner query.

If the subquery returns at least one row, the operator returns TRUE. If the value does not exist, it returns FALSE. Example: List all departments that have no employees: SELECT * FROM DEPT WHERE NOT EXISTS

(SELECT * FROM EMP WHERE DEPTNO = DEPT.DEPTNO); Explanation For each row from the table DEPT, the condition is checked whether there exists a row in the table EMP that has the same department number (DEPT.DEPTNO). In case no such row exists, the condition is satisfied for the row under consideration and it is selected. If there exists a corresponding row in the table EMP, the row is not selected. Limitation Oracle allows up to 255 levels of sub queries in the WHERE clause. CORRELATED SUBQUERY A subquery becomes correlated subquery when the subquery references a column from a table in the parent query. A correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE or DELETE. A correlated subquery is one way of reading every row in a table and comparing values in each row against related data. It is used whenever a subquery must return a different result for each row of the parent query. Example: List all those employees who are working in the same department as their manager. SELECT * FROM EMP E1 WHERE DEPTNO IN

(SELECT DEPTNO FROM EMP E WHERE E.EMPNO = E1.MGR);

Page 5: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 5 of 22

Note that an alias for the table EMP in the subquery is not necessary since columns without a preceding alias listed there always refer to the innermost query and tables. Example: Select all employees whose salary is less than the average of all the employees' salaries in the same department. SELECT ENAME, SAL ,DEPTNO FROM EMP A WHERE A.SAL <

(SELECT AVG(SAL) FROM EMP B WHERE A.DEPTNO = B.DEPTNO) ORDER BY DEPTNO;

Using a correlated sub query in an update Give a raise to those employees whose salary is less than their department's average.

UPDATE EMP A SET A.SAL = A.SAL + 500 WHERE A.SAL < (SELECT AVG (SAL) FROM EMP B WHERE A.DEPTNO = B.DEPTNO);

Using a correlated subquery in a delete

Delete the highest earning employees in each department.

DELETE FROM EMP A WHERE A.SAL = (SELECT MAX(SAL) FROM EMP B WHERE A.DEPTNO = B.DEPTNO);

*JOIN

The process of forming rows from two or more tables by comparing the contents of related columns is called “Joining” tables.

Joining column name may not be same but type and width must be same for all tables.

The purpose is to bind data together, across tables, without repeating all of the data in every table. Generally joining includes primary key of one table and foreign key of another table.

Connection between the tables is established using WHERE clause.

Types of JOIN

1. INNER / EQUI 2. OUTER (LEFT, RIGHT, FULL) 3. CROSS / CARTESIAN 4. SELF 5. NATURAL

1. INNER JOIN

INNER JOIN is also known as EQUI JOIN or SIMPLE JOIN.

When the joining condition in where clause compares two columns from two tables with equality operator ( = ), it is known as EQUI JOIN. Here, join formed as a result of exact match between two columns.

Page 6: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 6 of 22

SYNTAX

SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name ;

INNER JOIN is used to select only those rows which have common values in the columns specified in ON clause.

INNER JOIN returns all rows from both tables where there is a match. Example: SELECT * FROM EMP A, DEPT B WHERE A.DEPTNO = B.DEPTNO; NON-EQUI JOIN When a joining condition contains any operator other than equality operator like >, <, >=, <=, then the join is known as NON-EQUI JOIN.

2. OUTER JOIN If some values in one table do not have corresponding values then EQUI JOIN will not display those rows. Such rows can be displayed using OUTER JOIN. Corresponding columns for such rows will be displayed with NULL values. So, OUTER JOIN can be used when it is required to select all rows from the table on the left / right / both regardless of whether the other table has values in common and enter NULL where data is missing. 1) LEFT JOIN (LEFT OUTER JOIN)

LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2). SYNTAX SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name ;

OR

SELECT column_name(s) FROM table_name1, table_name2 WHERE table_name1.column_name (+) = table_name2.column_name; SQL outer join operator in Oracle (+) is used on left side of the join condition. 2) RIGHT JOIN

RIGHT JOIN keyword returns all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).

Page 7: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 7 of 22

SYNTAX SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name ;

OR

SELECT column_name(s) FROM table_name1, table_name2 WHERE table_name1.column_name = table_name2.column_name (+); SQL outer join operator in Oracle (+) is used on right side of the join condition. 3) FULL JOIN

FULL JOIN keyword return rows when there is a match in one of the tables. SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name ; 3. CROSS / CARTESIAN JOIN

If a join condition is not specified, Oracle performs a Cartesian product. Oracle combines each row of one table with each row of the other. It combines each row from left table with every row from the right table. For example, if EMP table contains 10 records and DEPT table contains 4 records, the number of rows selected by the query without a join condition produces 40 records. EXAMPLE

SELECT * FROM EMP, DEPT;

4. SELF JOIN

SELF JOIN is a type of SQL join which is used to join a table to itself. It is a join of two copies of same table.

It is generally used when the table has a FOREIGN KEY that references its own PRIMARY KEY.

It is necessary to ensure that the join statement defines an alias for both copies of the table to avoid column ambiguity.

Syntax of self join is same as other joins but the FROM clause is different. It contains same tables twice or more times. It is compulsory to prefix the column name with alias.

EXAMPLE

Display name of employees and names of their respective managers.

SELECT A.ENAME, B.ENAME FROM EMP A, EMP B WHERE A.MGR=B.EMPNO;

Page 8: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 8 of 22

*INDEXES Indexes are an ordered set of pointers to data in a table, stored separately from the table. When a select statement is fired to search for a particular record, the Oracle engine must first locate the table on the hard disk. The oracle engine then performs a sequential search to locate records that matches user-defined criteria as specified in the select. Indexing involves forming a two dimensional matrix completely independent of the table on which the index is being created. This two dimensional matrix will have a single column, which will hold sorted data, extracted from the table column(s) on which the index is created. Another column is called the address field identifies the location of the record in the oracle database. For every data value held in the index the oracle engine inserts a unique ROWID value. This is done for every data value inserted into the index, without exception. Indexes can be created on a single column or a group of columns. When an index is created, it first sorts the data and then it assigns a ROWID for each row. When the user is accessing a table, he/she need not be aware that SQL is using an index. Index in SQL is created on existing tables to retrieve the rows quickly. When there are thousands of records in a table, retrieving information will take a long time. Therefore indexes are created on columns which are accessed frequently, so that the information can be retrieved quickly. BENEFITS

Improves performance. Access to data is faster.

Ensures uniqueness.

Advantage of having index is that it greatly speeds the execution of SQL statement with search and that refer to the indexed column.

One disadvantage is it requires additional disk space.

Index must be updated every time row added to the table.

Indexing is more appropriate when query against a table are more frequent than insert and update.

When user drops primary key or unique key constraints or drop table, oracle automatically drop indexes on primary key column or unique key column or table itself.

Page 9: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 9 of 22

When to use INDEX

1. If a table has more than a few thousand rows then index it. 2. Index only simple columns. 3. Try not to create more than two or three indexes on a table. 4. Index frequently used columns.

CREATION OF AN INDEX An index can be created on one more columns. Based on the number columns included in the index, an index can be: 1. Simple index 2. Composite index

1. Simple index

An index created on a single column of a table is called a simple index. Syntax Create index <IndexName> ON <TableName> (<ColumnName>); Example Create indx_emp on emp (eno); 2. Composite index

An index created on more than one column is called a composite index. Syntax Create index <IndexName> ON <TableName>

(<ColumnName1>,<ColumnName2>); Example Create indx_emp on emp (eno,dno); TYPES OF SQL INDEX 1. Implicit Indexes - They are created when a column is explicitly defined with

PRIMARY KEY, UNIQUE KEY Constraint. 2. Explicit Indexes - They are created using the "create index.. " syntax. Oracle allows the creation of two types of indexes.

1. Duplicate Index It is an Index that allows duplicate values for the indexed columns 2. Unique Index It is an Index that deny duplicate values for the indexed columns i.e. Once unique index added to particular column then that column won’t allow you to inset duplicate values.

Page 10: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 10 of 22

If duplicate values present in particular column then oracle won’t allow creating index on that column. SYNTAX CREATE UNIQUE INDEX <INDEX NAME> ON <TABLE> (COLUMN NM1,…); Dropping an Index SYNTAX DROP INDEX <INDEX NAME>; NOTE 1. Even though SQL indexes are created to access the rows in the table quickly, they

slow down DML operations like INSERT, UPDATE, DELETE on the table.

Because the indexes and tables both are updated along when a DML operation is performed. So use indexes only on columns which are used to search the table frequently.

2. It is not required to create indexes on table which have less data.

3. In oracle database you can define up to sixteen (16) columns in an INDEX.

*VIEWS

Views are masks place upon tables.

Allows the programmer to develop a method via which we can display predetermined data to users according to our desire.

To make queries of table easier, oracle provide for generation of views.

View is created unique, according to need of each user, where user can then only access those fields of the database allowed by the view.

DBA treats a view just as it would treat base table i.e., were a base table.

Query fired on view runs faster than it were fired on base table, as view will be a subset of the total number of columns in the table.

View is a SQL query i.e., permanently stored in the database and assigned a name.

Result of stored query are “visible” the view and SQL lets you access these query results as if they were in fact real table in database.

“View is a kind of VIRTUAL TABLE in database whose content are defined by query”

View is logical table that allows you to access data from other tables and view.

View contains no data itself.

The table upon which a view is based is known as base table.

View lets you tailor the appearance of database so that different users see it from different perspective.

Views let you restrict access to data, allowing different users to see only certain rows / certain columns.

Dropping base table on which the view has been created will not drop the view but user can’t perform query against view.

Page 11: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 11 of 22

ADVANTAGES OF VIEWS 1. Security

Each user can be given permission to access database only the small set of views that contains the specific data, so restricting user to have an access of specific / required data instead of all data.

2. Query Simplicity View can be drawn from several tables and present it as single table, turning multiple table queries into single table queries against the views.

3. Structural Simplicity Views can be give user a “personalized” view of the database structure, presenting the database as a set if virtual tables that make sense for that user.

4. Insulation from Change Views can present a consistent, unchanged, image of structure of database, even if the underlying source tables are split, restructured or renamed.

5. Data Integrity If data is accessed and entered then view, the DBA can automatically checks the data to ensure that it meets specified integrity constraints defined on base table.

DISADVANTAGES OF VIEW 1. Performance

Views create the appearance of a table, but the DBMS must still translate queries against view into queries against tables (source table/base tables). If view is defined by complex, multiple table queries, then a simple query against view becomes a complicated join, & it may take long time to complete.

2. Update Restriction When user tries to update rows of a view, the DBMS must translate request into an update on rows of the underlying source/base table.

This is possible for simple views, but more complex views can’t be updated, they are read-only.

Views may be created for the following reasons. 1. DBA stores the views as a definition only. Hence, no duplication of data. 2. Simplifies queries. 3. Can be queried as a base table itself. 4. Provides data Security. 5. Avoids data redundancy.

Page 12: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 12 of 22

SYNTAX CREATE [ OR REPLACE ] VIEW <VIEW NAME> AS <QUERY> [ [WITH] READ ONLY] EXAMPLE CREATE VIEW VW_EMP AS SELECT EMPNO, ENAME, JOB, MGR FROM EMP;

CREATE VIEW VW_EMP1 AS SELECT EMPNO, ENAME, JOB FROM EMP WHERE JOB IN (‘MANAGER’,’ANALYST’); UPDATABLE VIEW

View can also be used for data manipulation i.e. user can perform INSERT, UPDATE or DELETE operation on view such views are called UPDATABLE VIEWS.

Views that do not allow data manipulation are called Read only View, Non-updatable view.

If view is updatable the changes made to view data will pass that to base table on which the view has been created.

View is updatable if 1. Must be created on a single table. 2. Primary Key column of table must be included. 3. {} function can’t be used in select statements. 4. SELECT statement used for creating view should not include DISTINCT, GROUP

BY or HAVING clause. 5. SELECT statement used for creating view should not included use of sub-queries. 6. If view is defined from another view, the second view should be updateable. 7. It must not use constraints, strings or value expression like sell_price, i.e. calculated

column. 8. For insert, it should include all NOT NULL fields.

DROPPING VIEW DROP view <view name>; COMPLEX VIEW 1. Create view vw_emp (eno,enm,join_dt,salary)

as select empno,ename,Hiredate,Sal from emp; 2. Create view view_emp (empno,ename,n_sal)

as select empno,ename,sal*0.15 from emp; 3. Create view vw_mon_sal_emp_dat(deptno,sum_sal)

as select deptno,sum(Sal) from emp group by deptno;

Page 13: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 13 of 22

*SEQUENCES Oracle provides an object called sequence that can generate numeric values. The value generated can have a maximum of 38 digits. A sequence can be defined to: 1. Generate numbers in ascending an descending order. 2. Provide interval between numbers. 3. Caching of sequence numbers in memory to speed up their availability.

SYNTAX CREATE SEQUENCE <sequenceName> [ INCREMENT BY <IntegerValue> START WITH <IntegerValue> MAXVALUE <IntegerValue>/ MAXVALUE MINVALUE <IntegerValue> / MINVALUE CYCLE / NOCYCLE CACHE <IntegerValue> / NOCHE ORDER / NOORDER ] Keywords and parameters

INCREMENT BY Specifies the interval between sequence numbers. It can be any positive, negative value but not a zero. Default value is 1.

MINVALUE Specifies the sequence minimum value.

NOMINVALUE Specifies a minimum value of 1 for an ascending sequence. And 10^26 for descending sequence.

MAXVALUE Specifies the maximum value that a sequence can generate.

NOMAXVALUE Specifies a maximum 10^27 for an ascending sequence or -1 for a descending sequence. This is the default clause.

START WITH Specifies the first sequence number to be generated.

CYCLE Specifies that the sequence continues to generate repeat values after reaching either its maximum value.

NOCYCLE Specifies that a sequence cannot more values after reaching the maximum value.

CACHE Specifies how many values of a sequence Oracle pre-allocates and keeps in memory for faster access.

NOCACHE Specifies that the values of a sequence are not pre-allocated.

ORDER This guarantees that sequence numbers are generated in the order of request. This is only necessary if using a parallel server in parallel mode option.

NOORDER This does not guarantee sequence numbers are generated in order of request. This is only necessary if using a parallel server in parallel mode option. The default is NOORDER clause.

Page 14: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 14 of 22

EXAMPLE

CREATE SEQUENCE SEQ_1 INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 999 CYCLE;

REFERRING A SEQUENCE

Once a sequence is created then use NEXTVAL and CURRVAL columns to view the values held in cache.

SYNTAX

1. Select < sequence_name>.nextval from dual; 2. Select < sequence_name>.currval from dual;

EXAMPLE SELECT SEQ1.NEXTVAL FORM DUAL;

Every time NEXTVAL references a sequence its output is automatically incremented from old value to new value. *SYNONYM

A synonym is an alternative name for objects such as Table, view, sequence, stored procedure, stored function, package, java class and another synonym.

Synonym is an alias for one of the objects.

The object does not need to exist at the time of its creation.

Synonyms cannot be used in a drop table, drop view or truncate table statements. If this is tried, it results in a oracle that table or view does not exist

Synonyms provide both data independence and location transparency.

You can refer to synonyms in the following DML statements: SELECT, INSERT, UPDATE, DELETE and LOCK TABLE.

SYNTAX

CREATE [OR REPLACE] [PUBLIC] SYNONYM [SCHEMA .] SYNONYM_NAME FOR [SCHEMA .] OBJECT_NAME ;

CREATE

Use the CREATE SYNONYM statement to create a synonym, which is an alternative name of objects.

OR REPLACE

OR REPLACE phrase allows you to recreate the synonym (if it already exists) without having to issue a DROP synonym command.

PUBLIC PUBLIC phrase means that the synonym is a public synonym and is accessible to all users. Remember though that the user must first have the appropriate privileges to the object to use the synonym.

Page 15: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 15 of 22

SCHEMA SCHEMA phrase is the appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own schema.

OBJECT_NAME

OBJECT_NAME phrase is the name of the object for which you are creating the synonym.

EXAMPLE 1. create or replace synonym emp1 for emp; 2. create or replace synonym sb1.dept for dept; 3. create or replace public synonym emp11 for emp11; If this synonym already existed and you wanted to redefine it, you could always use the or replace phrase .(example-3) USE OF SYNONYM Using the select statement we can use the synonym. Select * from synonym_name; Example: select *from emp11; DROPPING A SYNONYM It is also possible to drop a synonym. SYNTAX DROP [PUBLIC] SYNONYM [SCHEMA .] SYNONYM_NAME [FORCE];

DROP Use the drop statement to drop a synonym.

PUBLIC PUBLIC phrase allows you to drop a public synonym. If you have specified public, then you don't specify a schema.

SCHEMA SCHEMA phrase is the appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own schema.

FORCE FORCE phrase will force Oracle to drop the synonym even if it has dependencies. It is probably not a good idea to use the force phrase as it can cause invalidation of Oracle objects.

EXAMPLE

1. drop synonym emp1; 2. drop synonym sb1.dept; 3. drop public synonym emp11;

Page 16: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 16 of 22

*DATA CONTROL LANGUAGE STATEMENTS (GRANT and REVOKE) DCL commands are used to enforce database security in a multiple user database environment. Two types of DCL commands are GRANT and REVOTE. Only Database Administrator's or owners of the database object can provide / remove privileges on a database object. *GRANT SQL GRANT is a command used to provide access or privileges on the database objects to the users. SYNTAX GRANT privilege_name ON object_name TO { user_name | PUBLIC | role_name } [WITH GRANT OPTION];

privilege_name It is the access right or privilege granted to the user. Some of the access rights are ALL, EXECUTE, and SELECT.

object_name It is the name of an database object like TABLE, VIEW, STORED PROC and SEQUENCE.

user_name It is the name of the user to whom an access right is being granted.

PUBLIC It is used to grant access rights to all users.

ROLES They are a set of privileges grouped together.

WITH GRANT OPTION

It allows a user to grant access rights to other users.

EXAMPLE GRANT SELECT ON employee TO user1; This command grants a SELECT permission on employee table to user1. Note You should use the WITH GRANT option carefully because: For example if you GRANT SELECT privilege on employee table to user1 using the WITH GRANT option, then user1 can GRANT SELECT privilege on employee table to another user, such as user2 etc. Later, if you REVOKE the SELECT privilege on employee from user1, still user2 will have SELECT privilege on employee table.

Page 17: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 17 of 22

*REVOKE REVOKE command removes user access rights or privileges to the database objects. SYNTAX REVOKE privilege_name ON object_name FROM { user_name | PUBLIC | role_name } EXAMPLE REVOKE SELECT ON employee FROM user1; This command will REVOKE a SELECT privilege on employee table from user1. When you REVOKE SELECT privilege on a table from a user; the user will not be able to SELECT data from that table anymore. However, if the user has received SELECT privileges on that table from more than one user, he/she can SELECT from that table until everyone who granted the permission revokes it. You cannot REVOKE privileges if they were not initially granted by you. ROLES Roles are a collection of privileges or access rights. When there are many users in a database it becomes difficult to grant or revoke privileges to users. Therefore, if you define roles, you can grant or revoke privileges to users, thereby automatically granting or revoking privileges. *TRANSACTION CONTROL LANGUAGE STATEMENTS (COMMIT, ROLLBACK and SAVEPOINT) There are 2 SQL-Transaction Statements: COMMIT Statement -- commit (make persistent) all changes for the current transaction ROLLBACK Statement -- roll back (rescind / cancel) all changes for the current transaction *COMMIT Statement The COMMIT Statement terminates the current transaction and makes all changes under the transaction persistent. It commits the changes to the database. SYNTAX COMMIT [WORK] WORK is an optional keyword that does not change the semantics of COMMIT.

Page 18: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 18 of 22

*ROLLBACK Statement ROLLBACK Statement terminates the current transaction and rescinds all changes made under the transaction. It rolls back the changes to the database. SYNTAX ROLLBACK [WORK] WORK is an optional keyword that does not change the semantics of ROLLBACK. *SAVEPOINT SYNTAX <savepoint_statement> ::= SAVEPOINT <sql_savepoint_name> SAVEPOINT statement opens a sub-transaction. This means the database system records the current position (SQL savepoint) in the transaction and assigns it the name SQL_savepoint_name. The SQL savepoint is identified as active. Any sequence of SQL statements can then follow within one transaction. The sequence of SQL statements can contain other SAVEPOINT statements; however, no more than 50 SQL savepoints can be active in one transaction. Names of SQL savepoints in a transaction must be different. If an SQL savepoint name is assigned twice within a transaction, the SQL savepoint in this transaction defined by the first SAVEPOINT statement becomes inactive. ROLLBACK TO Statement SYNTAX <rollback_to_statement> ::= ROLLBACK TO [SAVEPOINT] <sql_savepoint_name> A ROLLBACK TO statement reverses all database modifications made in the active transaction following the SAVEPOINT statement. The SQL savepoint specified in the ROLLBACK TO statement must be an active SQL statement in the transaction. All SQL savepoints created after this SQL savepoint are inactive. All SQL savepoints created before this SQL savepoint remain active. The specified SQL savepoint also remains active after the ROLLBACK TO statement has been executed. This means the ROLLBACK TO statement can be executed in the same transaction more than once by specifying the same SQL savepoint name.

Page 19: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 19 of 22

*REPORT COMMANDS Reports are produced by storing commands to a file that can be executed by using the SQLPLUS START command. You may use whatever editor you prefer to create the report file. 1. REMARK This command can be shortened to REM. SQLPLUS ignores anything on a line that begins with REM to allow you to document your program file.

2. SET HEADSEP This is a Heading Separator command to tell SQLPLUS how you will indicate where you wish to break a page or column heading that is more than one line. The default is the vertical bar (|), but if your keyboard does not have this, use this command to select another character like the exclamation point.

Example: set headsep ! 3. TTITLE and BTITLE TTITLE stands for top title at the top of each page of a report. Example: ttitle 'Sales by Month During 2000 | Second Half of the Year' This example produces a two line split title that is centered on each page of a report. It also default places the day, month, and date the report was run in the upper-left corner of the top title, and the page number in the upper-right corner of the top title. BTITLE command is for the bottom of each page and centers the output on each page. Example: btitle 'Doug's Report' 4. COLUMN This command allows you to change the heading and format of a column that is in a SELECT statement. Example: Column Item heading 'What Was | Sold'

Column Item format A18 This example produces a two-line heading for the column named ITEM, and the following command sets ITEM to alpha, 18 columns of output, with all characters after 18 being word wrapped to the next line.

Page 20: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 20 of 22

If you want all after 18 characters to be truncated, the command is: Column Item truncated Combining these commands: Column Item heading 'What Was | Sold' format a18 truncated Example Formatting a number Column Rate format 90.99 It will always print a zero in the dollars position for amounts that are less than 1.00: CREATING A NEW COLUMN SELECT Quantity, Rate, Quantity * Rate "Ext" from Ledger It wil create a new column that consists of Quantity * Rate and name the column Ext. This is a virtual column. 5. BREAK ON To produce grouping of items as in a control break report, use the BREAK ON command, in conjunction with the ORDER BY option in the SELECT command.

Example: Break on Item skip 2 SQLPLUS will examine each row and track the value in Item. When the value for Item changes, SQLPLUS will skip two lines. Also the value for Item is printed on the first line of its section to eliminate duplicate printing of each of these items for every row in each section. If you want a grand total for the report, use the command: Break on Item skip 2 on report If you just use BREAK ON report, then the second BREAK ON command will override the first one. 6. COMPUTE SUM This calculates totals for each section of the report. It will always total for the field specified in the BREAK ON command. This will compute the total sum of the values of Ext for each Item. This command must be used in conjunction with the BREAK ON command. Treat them as a single unit of two related commands.

Example: Break on Item skip 2 on report

Compute sum of Ext on Item

Page 21: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 21 of 22

Note:

Every BREAKON must have a related ORDER BY

Every COMPUTE SUM must have a related BREAK ON 7. SPOOL Spooling a file is writing the file to a print queue To name the output file for your report, use the SPOOL command. We usually use a default filename extension of lst (stands for listing).

Example: Spool myoutputfile.lst

Place this command just before your SELECT command in a report producing program.

Place SPOOL OFF directly after the SELECT command. This turns spooling off so that output quits going to the output file.

You can also use spooling to create a program file, but all of the output including messages produced by SQLPLUS will go to the file.

This is also a good way to capture error messages. 8. /* */ REMARKS

Use this option to embed comments in an SQL statement. Everything within the symbols is treated as a remark. 9. SET PAUSE You can cause the report to display exactly one full screen at a time. Put these command in your login.sql file so that they automatically execute every time you load SQLPLUS. Example: set pause 'More . . .'

set pause on

10. START

This command is used to execute an SQL report file. Use the filename extension of SQL for your program files. Example: Start myreportfile.sql

Page 22: CHARUTAR VIDYA MANDAL’S SEMCOM Vallabh … unit-4.pdfA correlated subquery is evaluated once for each row processed by the parent statement. Parent statement can be SELECT, UPDATE

US03CBCA01 (Relational Database Management Systems - I) Unit - IV

Page 22 of 22

*CHECKING THE SQLPLUS ENVIRONMENT CHECKING VALUES OF COMMANDS You can check the values of various commands, usually by just typing the command. Examples: Column Item : will display the instructions about the column named Item Ttitle : will display instructions about the TTITLE command value Btitle : will display instructions about the BTITLE command value Compute : will display information about the COMPUTE command value USING SHOW Use the SHOW command to display information about values that were set with the SET command. Show headsep Show linesize Show pagesize Show newpage DISABLING COMMANDS and CLEARING VALUES Ttitle off will turn this command off. Btitle off will turn this command off. Clear columns will clear the values stored for all columns. Clear breaks will clear all values for breaks. Clear computes will clear all values for computes. Disclaimer The study material is compiled by Ami D. Trivedi. The basic objective of this material is to supplement teaching and discussion in the classroom in the subject. Students are required to go for extra reading in the subject through library work.