Professional Documents
Culture Documents
The Oracle Server Provides an open comprehensive and integrated approach to information management an oracle
server consists of an oracle database and an oracle instant every time a database is started in the System Global Area -
SGA is allocated and oracle background processes are also started the System Global Area is an area of memory used
for database information shared by the database users the combination of the background processes and memory
buffers is called and oracle instance.
SQL Statements
Projection - Choose the columns in a table that you want returned by your query.
Selection - Choose the rows in a table that you want returned by your query.
Joining - To bring together data that is stored in different tables by creating a link between them.
Arithmetic Expressions
Low Priority High Priority
Add + Subtract - Multiply * Divide /
Page 1
Using Literal Character Strings
( ' ' ) Single Quotation Marks
eg:- Select last_name || ' is a ' || job_id as "Employees Details" from employees ;
eg:- Select last_name || ' :- Salary = ' || salary as " Monthly Salary " from employees ;
Page 2
Using Logical Conditions
Rules of Percedence
Page 3
SQL Functions
Two Type of SQL Functions
Single - Row Functions Multiple
È - Rows Functions
These Function operate on single row These Functions can manipulate groups
only and retruns one result per row. of rows to give one result per group of rows.
Characters
Number
Date
Conversion
General
Function_Name (arg1,arg2)
Functions
Character Functions General Functions Date Functions Number Functions
Single-Row Functions
* Manipulate data items
* Accept arguments and return one value
* Act on each row returned
* Return one result per row
* May modify the data type
* Can be nested
* Accept arguments which can be a column or an expression Function_Name[(arg1,arg2,....)]
* Can be used in select, where, and order by clauses; can be nested.
In the Syntax :
Function_Name is the name of the function. arg1,arg2 is argument to be used by the function this can be represented
by a column name or expression.
Page 4
Character Functions
Initcap - Coverts alpfa character values to upper case for the first letter of each world, all other letters in lower case.
eg:- Select Initcap(job_id) from employees ;
Concat - Joins values together (You are Limited to using two parameters with concat)
eg:- Select Concat(last_name,first_name) from employees ;
Trim - Trim heading or trailing character (or both) from a character string.
If trim_character or trim_source is a character literal, you must enclose it in sigle quotes.
eg:- Select Trim('H' from last_name) from employees ;
Number Functions
Dual is a Dummy Table.
Page 5
Working With Dates
* Oracle Database Stores dates in an internal numeric format :-
Centurys - Years - Months - Days - Hours - Minutes - Seconds
* The default data display format is DD-MON-RR
* The default display input format for and date is DD-MON-RR.
Vaild oracle dates are between January 1,4712 B.C and December 31,9999 A.D
* This data is stored intenally as follows :-
Centurys - Years - Months - Days - Hours - Minutes - Seconds
19 94 06 07 5 10 43 :- June 7th, 1994 5:10:43 PM
Fmt - If the format model Fmt is omitted, date is rounded to the Nearest Day.
All eg:-
Select employee_id,hire_date,
Months_Between (sysdate,hire_date) ,
Add_Months (hire_date,2) ,
Last_Day (hire_date)
From employees
Where hire_date like '%94%' ;
Page 6
Conversion Function
Data Types Conversion
RR Date Format
Oracle have one main function saving date and time by oracle it self in century when you insert any record it take
default date and time but in other way like DD-Mon-RR is the format of oracle.
Day-Month-Century Year Hrs Min Sec .This DD-Mon-RR is Nice to by time zone also and it show the year in which
your are working like in 21 Century of 2009.
DD-Mon-RR
eg:- Select last_name, To _Char(hire_date,'DD-Mon-YYYY)
From employees
Where hire_date < To_Date ('01-Jan-90','DD-Mon-RR) ;
eg:- Select last_name, To_Char(hire_date,'DD-Mon-YYYY)
From employees
Where To_Date(hire_date,'DD-Mon-YY') < '01-Jan-1990' ;
Page 7
Format elements of vaild Date, Time and Number Formats :-
Date Format :
Time Format :
AM or PM - Meridian indicator
A.M or P.M - Meridian indicator with period
HH or HH12 or HH24 - Hours of day or Hours (1-12) or Hours (0-23)
MI - Minute (0-59)
SS - Second (0-59)
SSSS - Second past minight (0-86399)
Number Fromat :
Page 8
Nesting Functions
* Single-row function can be nested to any level.
* Nested functions are evaluated from deepest level to the least deep level.
Step1=Result1
Step2=Result2
Step2=Result3
General Function
These function work with any Data type and pertain to using Null.
NVL2 - If expr1 is not null, NVL2 returns expr2 If expr1 is Null,NVL2 returns expr3.
The argument expr1 can have any data type.
eg:- Select last_name, salary, commission_pct, NVL2(commission_pct,'sal+com','sal') as Income
From employees Where department_id in (50,80) ;
NULLIF - Compares two expressions and returns Null if they are equal, or the first expression if theyare not equal.
Note:- The NULLIF Function is logically equivalent to the following case expression.
The case expression is discussea in a subsequent pages Case when expr1=expr2 Then Null else expr1 end
eg:- Select first_name, length(first_name) as "expr1", last_name, length(last_name) as "expr2",
NULLIF(length(first_name),length(last_name)) as Result from employees ;
Coditional Expressions
Case Expression
Page 9
Decode Function
Decode (column|expression,search1,result1[,search2,result2,....,][,default])
eg:- Select last_name, job_id, salary,
Decode (job_id, 'IT_Prog' , 1.10*salary ,
'ST_Clerk' , 1.15*salary ,
'SA_Rep' , 1.20*salary , salary ') "Revised Salary" From employees ;
eg:- Select last_name, salary,
Decode (Trunc(salary/2000,0),
0,0.00,
1,0.09,
2,0.20,
3,0.30,
4,0.40,
5,0.42,
6,0.44,
0.45) "Tax Rate"
From employees Where department_id = 80 ;
Types of Joins
Oracle Proprictary Joins (8i & Prior): SQL:1999 Compliant Joins:
Equijoin = Cross Joins
Non Equijoin Between...And Natural Joins
Outer Join (+) Using Clasuse
Self Join Full or Two Side Outer Joins
Aribitray Joins Conditions For Outer Joins
Equijoin
Note. Equijoin are also called simple joins or inner joins
eg:- Select table1.column, table2.column From table1 alias, table2 alias Where table1.column1 = table2.column2 ;
eg:- Select employee_id.emp,last_name.emp,department_id.dept,location_id.dept
From employees emp,departments dept
Where emp.department_id = dept.department_id ;
eg:- Select c.last_name,d.department_name,l.city
From employees e,departments d,locations l
Where e.department_id = d.department_id and d.location_id = l.location_id ;
Non Equijoins
Note. Retrieving records with non-equijoins
eg:- Select e.last_name,e.salary,j.grade_level From employees e,job_grades j
Where e.salary Between j.lowest_sal And j.highest_sal ;
Outer Joins
Note. The outer join operater si the plus sign(+)
eg:- Select e.last_name,e.department_id,d.department_name From employees e,departments d
Where e.department_id(+)=d.department_id ;
Self Joins
Note. Joining a table to it self
eg:- Select worker.last_name||' Works for '||manager.last_name From employees worker,employees manager
Where worker.manager_id = manager.employee_id ;
Page 10
SQL:1999 Compliant Joins:
Use a Join to query Data from more than one table.
Select table1.column,table2.column
From table1
[Cross Join table2] |
[Natural Join table2] |
[Join table2 Using (column_name)] |
[Join table2 On (table1.column_name = table2.column_name)] |
[Left | Right | Full Outer Join table2 On (table1.column_name = table2.column_name)] ;
Cross Joins
Note. The cross join clause produces the cross-product of two tables this is the same as a cartesian product between
the two tables.
eg:- Select last_name,department_name
From employees
Cross Join department ;
Natural Joins
Note. The Natural Joins clause is based on all columns in the tables that have the same name. The join can happen only
on columns having the same names and data types in both the tables. But if the columns have the same name,but
different data types, then the Natural Join syntax causes an error.
eg:- Select department_id,department_name,location_id,city
From departments Natural Join locations ;
Page 11
Group Functions
What are Group Functions ?
Group Function operate on sets of rows to give one result per group.These sets may be the whole table or the table
split into group
Group Functions
Group by Having AVG
Count
Max
Min
Stddev
Sum
Variance
Note. You can use Distinct keyword in this function. All group function ignore Null values in the column
you can use other like NVL , NVL2 etc...
Page 12
Subquery can be wirten single-row and multiple-row sub queries.
eg:- Select select_list From table Where expr operater (Select select_list From table) ;
eg:- Select last_name From employees Where salary >
(Select salary From employees Where last_name = 'Abel' ) ;
Type of Subqueries
Note. The outer and inner queries can get data from defferent tables.
Substitution Variables
Temporarily Store Values
- Single Ampersand (&)
- Double Ampersand (&&)
- Define Command
Pass Variable values between SQL Statements Dynamically alter headers and footers
Page 13
Use Set Commands to control current session
eg:- Set system_variable values
To see all set variable values, use the show all Command
eg:- Show All
eg:- Ttitle No/Off
Ttitle 'string'
Btitle 'string'
Insert
Insert into table [(column[,column...])]
Values (values[,value...]) ;
eg:- Insert into employees
( employee_id, first_name , last_name, email, phone_number,
hire_date, job_id, salary, commission_pct, manager_id, department_id )
Values ( 113, 'Louis', 'Popp', 'Lpopp', ' 515.124.4569', sysdate, 'Ac_Account', 6900, Null, 205, 100 ) ;
Insert statement with a subquery
eg:- Insert into sales_reps (id,name,salary,commission_pct)
Select employee_id,last_name,salary,commission_pct From employees Where job_id like '%Rep%' ;
Note. Do Not use the Values Clause.
eg:- Insert into copy_emp Select * From employees ;
Page 14
The Delete Statement
You can remove existing rows from a table by using the delete statement.
Delete [From] table_name [Where Condition(s)] ;
Deleting rows from a table specific rows are deleted if you specify the where clause.
eg:- Delete From departments Where department_ name = 'Finance' ;
1 row deleted
All rows in the table are deleted if you omit the where clause.
eg:- Delete From copy_emp ;
22 rows deleted
Deleting rows based on another table use subqueries in delete statements to remove rows from a table based on values
from another table.
eg:- Delete From employees Where department_id =
(Select department_id From departments Where department_name like '%Public%') ;
1 row deleted.
Deleting rows integrity constraint error
error:- Delete From departments Where department_id 60 ;
Delete From * departments
error at line 1:
ORA 02292: Integrity constraint (Hr.emp_dept_fk)
Voilated child record found
Page 15
Merging Rows
Insert or Update rows in the copy_emp table to match th employees.
eg:- Create Table copy_emp as Select * From employees ;
Delete From copy_emp ;
Merge Into copy_emp c
Using employees e
On (c.employee_id = e.employee_id)
When Matched Then
Update Set
c.first_name = e.first_name,
c.last_name = e.last_name,
c.email = e.email,
c.phone_number = e.phone_number,
c.hire_date = e.hire_date,
c.job_id = e.job_id,
c.salary = e.salary,
c.commission_pct = e.commission_pct,
c.manager_id = e.manager_id,
c.department_id = e.department_id,
When Not Matched Then
Insert Values ( e.cemployee_id, e.first_name, e.last_name, e.email, e.phone_number,
e.hire_date, e.job_id, e.salary, e.commission_pct, e.manager_id, e.department_id ) ;
Select * From copy_emp ;
Commit end the current transaction by making all pending data changes permanet
Rollback rollbsck ends the current transaction by discarding any changes and or savepoints created after the
savepoints to which you are rolling back if you omit the to savepoints clause the rollback statement rolls
back the entire transations. As savepoints are logical, there is no way to list the savepoints you have created.
Note. Savepoint is not ANSI Standard SQL .
Controlling Transactions
Savepoint, Commit and Rollback with only DML Statment Insert, Update, Delete, Merge.
Time Commit
Transaction
Delete Statement
Savepoint A
Insert Statement
Update Statement
Savepoint B
Insert Statement
Commit
Page 16
eg:- Select * From employees ;
Insert into departments Values(290,'corporate Tax',Null,1700) ;
1 row inserted
Delete From employees
Where employee_id = 9999 ;
1 row deleted
Commit ;
commit complete
or
Rollback ;
rollback complete
Createing Table
eg:- Create Table dept ( deptno number(2), dname varchar2(14), loc varchar2(13) ) ;
Table Created.
Confirm Table Creation
Describe dept
Prefix Description
User_ - These views contain information about object owned by the user.
All_ - These views contain information about all of the tables (object tables and relational tables) accessible to the
user.
DBA_ - These views are restircted views which can be accessed only by user who have been assigned the DBA role.
V$ - These views are dynamic performance views database server performance, memory and locking
eg:- Select table_name From user_tables ; // See the names of tables owened by th users.
eg:- Select Distinct object_type From user_objects ; // View distinct object types owned by the users.
eg:- Select * From user_catalog ; // View tables views,synonyms and sequences owned by the users.
Data Types
Prefix Description
Varchar(size) Variable length character data
Char(size) Fixed length character data
Number(p,s) Variable length numeric data
Date Data & Time Jan 1,4712,BC and Dec 31,9999,AD
Long Variable legth character data up to 2 Gigabytes
Clob Character data up to 4 Gigabytes
Raw and Long Raw Raw binary data
Blob Binary data up to 4 Gigabytes
Bfile Binary data stored in an external file up to 4 Gigabytes
RowID A-64 base number system representing the unique
Note. A long column is not copied when a table is created using a sub query.
Page 18
Timestamp with time zone data type
* Timestamp with Time Zone is a variant of timestamp that includes a time zones displacement in its value.
* The Time Zone displacement is the difference, in hours and minutes, between local time and UTC.
Timestamp [(Fractionl_seconds_precision)] with Time Zone
eg:- Timestamp '1999-04-15 8:00:00 -8:00'
Timestamp '1999-04-15 11:00:00 -5:00'
Timestamp '1999-04-15 8:00:00 US/Pacific' ;
* Alter Table table_name Add (column datatype [Default expr] [,column datatype]...) ;
* Alter Table table_name Modify (column datatype [Default expr] [,column datatype]...) ;
Note. If a table already contains rows when a column is added, then the new column is initially null for all the rows.
Page 19
The Set Unused option
* You use the set unused option to mark one or more columns as unused.
* You use the Drop unused columns option to remove the columns that are marked as unused.
Alter Table table_name Set Unused (column) ;
Alter Table table_name Set Unused column, column ;
Alter Table table_name Drop unused columns ;
eg:- Alter Table dept80 Set Unused (job_id) ;
eg:- Alter Table dept80 Drop Unused job_id ;
Dropping a Table
* All data and structure in the table is deleted.
* Any pending transaction are committed.
* All indexes are dropped.
* You connot roll back the drop table statement.
Drop Table table_name ;
eg:- Drop Table dept80 ;
Table Dropped.
Changing the Name of an object
* To change the name of a table,view,sequence or synonym you execute the rename statement
Rename dept To detail_dept ;
Table Renamed.
Truncating a Table
* The Truncate Table statement
- Removes all rows from a table
- Releases the storage space used by that table
Truncate Table detail_dept ;
Table Truncated.
* You connot roll back row removal when using Truncate.
* Alternatively, you can remave rows by using the delete statement.
Including Constraints
What are Constraints ?
* Constraints enforce rules at the table level.
* Constraints prevent the deletion of a table if there are dependencies.
* The Following constraints types are vaild
Code Constraints Description
NNK Not Null Specifies that the column connot contain a null value.
UK Unique Specifies a column or combination of columns whose values must be unique for all rows
in the table.
PK Primary Key Uniquely identifies each row of the table.
FK Foreign Key Establishes and enforeces a foreign key relationship between the column and a column of the
refernced table.
Check Specifies a condition that must be true.
Note.
* Name a constraint or the oracle server generates a name by using the sys_cn format.
* View a constraint in the data dictionary.
* You con view the constrants defined for a specific table by lookig at the User_Constraints data dictionary table.
Page 20
Defining Constraints
Create Table [Schema.] table
( column datatype [ Default [ column_constraint ] , expr ] .... [ table_constraint ] [ ,... ] ) ;
eg:- Create table employees ( employee_id Number(6),
first_name Varchar(20),.... job_id Varchar2(10) Not Null
Constraint emp_emp_id_pk primary key (employee_id) ) ;
* Column constraints level column [Constraint constraint_name] constraint_type,
* Table constraint level column,.... [constraint constraint_name] constraint_type(column,....),
Page 21
The Check Constraint
* Defines a condition that each row must satisfy
* The following expressions are not allowed :
- References th Currval , Nextval , Level and Rownum pseudocolumns.
- Calls th Sysdate , UID , User and UserENV Functions.
- Queries that refer to other values in other rows.
......, salary Number(2)
constraint emp_salary_min Check (salary > ) ,.......
Adding a Constraint
Use the Alter Table statements
* Add or Drop a constraint, but not modify it structures.
* Enable or Disable constraints.
* Add a Not Null constraint by using the modify clause.
Alter Table table_name
Add [constraint constraint_name] type (columns) ;
Note. You can define a Not Null column only if the table is empty or if the column has a value for every row.
Dropping a Constraint
* Remove the manager constraint from the employees table
eg:- Alter Table employees
Drop Constraint emp_manager_fk ;
* Remove the Primary Key
eg:- Alter Table departments
Drop Primary Key Cascade ;
Disabling Constraints
* Execute the Disable clause of the Alter Table statement to deactivate an integrity constraint.
* Apply the cascade option to disable dependent intergrity constraints.
eg:- Alter Table employees
Disable Constraint emp_emp_id_pk Cascade ;
Enabling Constraints
* Activate an integrity constraint currently disabled in the table definition by using the Enable clause
eg:- Alter Table employees
Enable Constraint emp_emp_id_pk ;
Cascading Constraints
* The cascade constraints clause is used along with the drop columns clause.
* The cascade constraints clause drops all referntial integrity constraints that refer to the primary and unique key
defined on the dropped columns.
* The cascade constraints clause also drops all multicolumn constraints defined on the dropped columns.
Note. This statements illustrates the usage of the cascade constraints cluase.Assume table Test1 is created as following:
Page 22
eg:- Create Table Test1
(PK Number Primary Key,
FK Number,
Col1 Number,
Col2 Number,
Constraint FK_constraints Foreign Key(FK)
References Test1,
Constraint CK1 Check (PK > 0 and Col1 > 0),
Constraint CK2 Check (Col1 > 0) ) ;
An Error is returned for the following statements.
Alter Table Test1 Drop (PK) ; - - pk is a parents key
Alter Table Test1 Drop (Col) ; - - Col Check
Cascading Constraints
eg:- Alter Table Test1
Drop (PK) Cascade Constraints ;
eg:- Alter Table Test1
Drop (PK,FK,Col1) Cascade Constraints ;
Viewing Constraints
Query the User_constraints table to view all constraints definitions and names
eg:- Select constraint_name, constraint_type, search_cindition
From User_Constraints
Where table_name = 'employees' ;
Note. Constraints that are not named by the table owner receive the system assigned constraint name,
In constraint type, C stands for Check,
P for Primary Key,
R for Referential integrity Foreign Key,
U for Unique Key.
Note. That Not Null constraint is really a check constraint.
Creating Views
* Views Logically represents subsets of data from one or more tables
* You embed a subquery within the create view statement
Create [Or Replace] [Force|NoForce] View view_name
[(alias[,alias]....)]
As Subquery
[With Check option [Constraint constraint_name] ]
[With Read Only [Constraint constraint_name] ] ;
* The subquery can contain complex select.
Create View
eg:- Create View empvu80
As Select employee_id , last_name , salary
From employees
Where department_id = 80 ;
View Created.
Create View with Aliases in Subquery
eg:- Create View salvu50
As Select employee_id Id_Number, last_name Name, Salary*12 Ann_Salary
From employees
Where department_id = 50 ;
View Created.
Page 23
eg:- Create View Salvu50 (Id_Number,Name,Ann_Salary)
As Select employee_id, last_name, salary*12
From employees
Where department_id = 50 ;
View Created.
Select * From salvu50 ;
Note. You can See all Views in user account from User_Views
Modifying a View
* Modify the empvu80 view by using create or replace view clause. Add an alias for each column name.
eg:- Create or Replace View empvu80
(id_number,name,sal,department_id)
As Select employee_id , first_name || ' ' || last_name,
From employees
Where department_id = 80 ;
View Created.
* Column aliases in the create view clause are listed in the same order as the columns in the subquery.
Inline Views
An Inline views is a subquery with an alias (or correlation name ) that you can use with in a SQL statement.
eg:- Select a.last_name, a.salary, a.department_id, b.maxsal
From employees a , (Select department_id max(salary) maxsal From employees Group by department_id) b
Where a.department_id = b.department_id and a.salary < b.maxsal ;
Page 24
Top N Analysis
* Top N Queries ask for the N largest or smallest values of a column. For example:
- What are the ten best selling products ?
- What are the ten worst selling products ?
* Both largest values and smallest values set are considered Top N Queries.
What is a Sequence ?
A Sequence
* Automatically genarates unique numbers
* Is a sharable objects
* Is typically used to create a primany key values
* Replaces application code
* Speeds up the efficiency of accessing sequence values when cached in memeory
Page 25
Using a sequence
* Insert new department named Support in location ID 2500
eg:- Insert into departments (department_id, department_name, location_id)
Values (dept_deptid_seq.Nextval, ' support ', 2500) ;
Select dep_detid_seq.Currval From Dual ; // 120
Modifying a Sequence
Change the increment value, maximum value, minmum value, cycle option or cache option.
eg:- Alter Sequence dept_depid_seq
Increment by 20
Maxvalue 999999
Nocache
Nocycle ;
Removing a Sequence
Remove a sequence from the data dictionary by using the drop sequence statement.
eg:- Drop Sequence dept_deptid_seq ;
Sequence dropped.
What is Index ?
An Index
* Is a schema object
* Is used by the oracle server to speed up the retrival of rows by using a pointer.
* Can reduce disk I/O by using a rapid path access method to locate data quickly.
* Is independent of the table it indexes.
* Is used and maintained automatically by the oracle server.
How are Indexes Created ?
* Automatically: A unique index is created automatically when you define a primary key or unique constraint
in a table columns definition.
* Manually: Users can create nonunique indexes on columns to speed up access to the rows.
Creating an Index
* Create an index on one or more columns.
Create Index index_name
On table_name (column[,column]...) ;
* Improve the speed of query access to the last_name column in the employees table.
eg:- Create Index emp_last_name_idx
On employees (last_name) ;
View User_ind_columns, User_indexes
Removing an Index
* Removing an Index from the data dictionary to using the drop index command.
Drop Index index_name ;
eg:- drop Index emp_last_name_idx ;
Index dropped.
Synonyms
Simplify access to object by creating a synonym (another name for an object) with the synonyms, you can
* Ease referring to a table owned by another user
* Shorten lengthy object names
Create [Public] Synonym synonym_name For object_name ;
* Creating and Removing Synonym create a shortened name for the dept_sum_vu view.
eg:- Create Synonym d_sum For dept_sum_vu ;
eg:- Drop Synonym d_sum ;
Page 26
Controlling User Access Privileges
* Database Security:
- Systen Secrity
- Data Secrity
* System privileges:
- Gaining access to the database
* Object privileges:
- Maniplating the content of the database objects
* Schemas:
- Collections of object such as table, View and Sequences
System Privileges
* More than too privileges are available
* The datebase administrator has high level system privileges for task such as:
- Creating New Users
- Removing Users
- Removing Tables
- Backing up Tables
Creating Users
* The DBA creates users by using the Create User Statment.
Create User user_name
Identified By Password ;
eg:- Create User Dinesh_user
Identified By Dinesh_B
User System Privileges
* Once a user is created the DBA can Grant specific system privileges to a user
Grant Privileges [,privileges...]
To User [,user/role, public...] ;
* An application developer for example, may have the following system privileges: View Session_privs
- Create Session To Connect the Database
- Create Table Create Table in the User's Schema
- Create Sequence Create a Sequence in User's Schema
- Create View Create a View in the User's Schema
- Create Procedure Create a Stored Procedure, Function or Package in the User's Schema
Granting System Privileges
The DBA can Grant a User Specifice System Privileges.
eg:- Grant Create Session, Create Table, Create Sequence, Create View
To Scott ;
What is a Role ?
Allocating Allocating
Privileges Privileges
Without a Role With a Role
Page 27
Creating and Granting Privileges to Role
Create a Role Create Session
eg:- Create Role dinesh_role ; Alter Session
Granting Privileges to Role Unlimited Tablespace
eg:- Grant Create Table, Create View Create Table
To dinesh_role ; Create Cluster
Granting Role to Users
eg:- Grant dinesh_role To dinesh_user ; Create Synonym
Changing your Password & Lock/Unlock Create View
Alter User scott Account Unlock Identified By tiger ; Create Sequence
Syntax: Create Database Link
Grant object_priv [(columns)] Create Procedure
On Object
To {User|Role|Public}
Create Trigger
[With Grant Option] ; Create Type
Granting Object Privileges Create Operator
* Grant query privileges on the employees table Create Index type
eg:- Grant Select
On employees
To sue, rich ;
View to See Privileges
eg:- Grant update (department_name, location_id) Session_privs
On departments Role_sys_privs
To scott,manager ; Role_tab_privs
Using the with Grant Option and Public Keyword User_role_privs
* Give a user authority to pass along privileges.
eg:- Grant Select,Insert
User_tab_privs_made
On departments User_tab_privs_recd
To scott User_col_privs_made
With Grant Option ; User_col_privs_recd
* Allow all users on the system to query data from alice's department tables. User_sys_privs
eg:- Grant Select
On alice.departments
To Publice ;
How to Revoke Object Privileges
* You use the Revoke statement to revoke privileges granted to other users.
* Privileges granted to others throgh the with grant option clause are also revoked.
Syntax:
Revoke {Privileges [,privileges....] | All}
On Object
From { user[,user...] | Role | Public }
[Cascade Constraints] ;
Revoking Object Privileges
* As user Alice, revoke the select and insert privileges given to user scott on the departments table.
eg:- Revoke Select,Insert
On departments
From scott ;
Database Links
* A database link connection allows local users to access data on a remote database
Local Remote
Page 28
Database Links
* Create the database link
Create Public Database Link HQ_acme.com
Using 'sales' ;
View: All_DB_links
eg:- Select * From emp@HQ.acme.com ;
Create Public Synonym HQ_emp For emp@HQ.acme.com ;
Select * From HQ_emp ;
Page 29
Datetime Functions ('Canada/Yakon')
* Display the time zone offset ('Europe/London Tz_offset
eg:- Select Tz_offset ('Us/Eastern') From Dual ; Current_date
Tz_offset ( ['time_zone_name']'[+/- hh:mm'] Current_timestamp
[sessiontimezone] [DBtimezone] )
Current_date
Localtimestamp
* Display the current data and time in the session's time zone. DBtimezone
eg:- Alter Session Session Time Zone
Set NLS_Date_Format = 'DD-Mon-YYYY, HH24:Min:Ss' ; Extract
eg:- Alter Session Set Time_zone = '-8:0' , '-5:0' ; From_Tz
eg:- Select Sessiontimezone, Current_date From Dual ;
eg:- Select Time_zone = '[+/-] hh:mm' From Dual ;
To_Timestamp
Current_timestamp To_Yminterval
* Display the current data and fractional time in the session's time zone. Timestamp with Time Zone (Ts Tz)
eg:- Alter Session Set Time_zone = '-5:0' ; current_timestamp (precision) Timestamp with Local Time Zone
eg:- Select sessiontimezone, current_timestamp From Dual ; (Ts Ltz)
Localtimestamp
* Display the current data and time in the session time zone in a value of timestamp datatype.
eg:- Alter Session Set Time_zone = '-5:0' ;
eg:- Select current_timestamp, localtimestamp From Dual ;
Timestamp [(Fractional_seconds_precision)] with Time Zone
Local_timestamp [(Fractional_precision)]
Dbtimezone and Sessiontimezone
* Display the Value of the database time zone
eg:- Select Dbtimezone From Dual ;
* Display the Value of the database time zone
eg:- Select sessiontimezone From Dual ;
Extract
* Display the year component form the sysdate.
eg:- Select Extract (Year From Sysdate) From Dual ;
Select Extract ( [Year] [Month] [Day] [Hour] [Minute] [Second] [Time Zone] [Timezone_minute]
[Timezone_resion] [Timezone_Abbr] )
From [datatime_value_expression] [ interval_value_expression] ;
From_Tz (timestamp timestamp_value, time_zone_value)
To_timestamp (char,[Fmt],['nlsparam'])
Time Interval conversion with to Minterval
* Display a date the is one year two months after the hire_date for the employees working in the department with
thedepartment_id = 20 :
eg:- Select hire_date, hire_date+To_yminterval('01-02') as From employees Where department_id = 20 ;
All Functions
* Tz_offset * Current_date
* From_Tz * Current_timestamp
* To_timestamp * Localtimestamp
* To_timestamp_tz * DBtimezone
* To_yminterval * Extract
Page 30
* Group data for obtaining the following
- Subtotal values by using the Rollup operator
- Cross-tobulation values by using the Cube operater
* Use the Grouping Function to Identify the level of aggregation in the result set
produced by a Rollup and Cube operator.
* Use Grouping Set to produce a single result set that is equivalent to a union all approach
Group by with Rollup and Cube
* Use Rollup or Cube with Group by to produce superaggregate rows by cross-referencing columns.
* Rollup grouping produces a results set containing the regular grouped rows and the subtotal values.
* Cube grouping produces a results set containing the rows from rollup and cross-tabulation rows.
Rollup
eg:- Select department_id, job_id, Sum(salary), NVL2(job_id,' ','Total')
From employees
Where department_id < 60
Group by Rollup (department_id, job_id) ;
Cube
eg:- Select Count(department_id), department_id, job_id, Sum(salary), NVL2(job_id,' ','Total')
From employees
Where department_id < 60
Group by Cube (department_id, job_id) ;
Grouping with Rollup and Cube
eg:- Select department_id dept_id, job_id job, Sum(salary),
Grouping (department_id) grp_dept,
Grouping (job_id) grp_job,
From employees
Where department_id < 50
Group by Rollup,Cube (department_id,job_id) ;
Grouping Sets
eg:- Select department_id, job_id, manager_id, AVG(salary)
From employees
Group by Grouping Sets
((department_id,job_id),(job_id,manager_id)) ;
Concatenated Grouping
eg:- Select department_id, job_id, manager_id, Sum(salary)
From employees
Group by department_id, Rollup (job_id), Cube(manager_id) ;
Page 32
Pivoting Insert
eg:- Insert All
into sales_info Values (employee_id,week_id,sales-mon)
into sales_info Values (employee_id,week_id,sales-tue)
into sales_info Values (employee_id,week_id,sales-wed)
into sales_info Values (employee_id,week_id,sales-thu)
into sales_info Values (employee_id,week_id,sales-fir)
Select employee_id,week_id,sales-man,sales-tue,sales-wed,sales-thu,sales-fir
From sales_source_date ;
External Tables
* External tables are read-only tables in which the data is stored outside the database inflat files.
* The metadata foran external table is created using a Create Table statement.
* With the help of external tables, oracle data can be stored or unloaded as a files.
* The data can be querid using SQL but you cannot use DML and no Indexes can be created.
Page 33
Controlling the Environment
Set echo OFF
Set Feedback OFF <= Set System Variable to appropriate values
Set Pagesize 0
Spool Dropem.sql
SQL Statement
Spool OFF
Set Feedback ON
Set Pagesize 24 <= Default System Value
Set echo ON
Page 34