Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
TIMESTAMP, INTERVAL DAY TO SECOND and INTERVAL YEAR TO MONTH can be used to
specify column definition.
SELECT empno,empname,NVL(jobid,’none’) from emp;oracle returns error cause:none value is not given as value
for number datatype ,if null is there in table with datatype string then ‘none’ can bedisplayed.
"Invoice" and "Invoice Items" Not Fk relation,It is "parrent -child relation" ,cause "one invoice can have more than
one items and none items also" which is OPTIONAL ,thats why here it is not Fk relation,It is Parrent Child Relation
exists.
"USED to change the default character indentifies runtime variable" SET DEFINE COMMAND
When null data fed into group functions then the result is always "NULL" like .......(SUM(SAL)......having sal values
as null ).
If we are executing mathamatical expressions on "user defined statistics" in our query,then where clause does not
indentify the component of a query.
If we use mathematical expression on "statistical expression" then where clause identifies: like(select * from emp
where empsal =6700-2?.....selects values of sal=6698)where clause identifies.
column padded to 7 digits right and have value SMITHY, So length of that column is "13" not "5".
Which SQL statement will return the ENAME, length of the ENAME, and the numeric position of the letter "a" in
the ENAME column, for those employees whose ENAME ends with a the letter "n"?
SELECT ENAME, LENGTH(ENAME), INSTR(ENAME, 'a') FROM EMPLOYEES WHERE SUBSTR(ENAME,
-1, 1) = 'n';
Top N analysis requires ROWNUM and ORDER BY,An INLINE view and an OUTER QUERY.
SELECT *
FROM emp
WHERE commission = (SELECT commission
FROM emp
WHERE emp_id = 3);Query returns no rows but not give any error
ROWID:a hexadecimal string representing the unique address of a row in its table
1
Two Date columns (SUBSTRACTION)MINUS will give numeric value.
Create synonym
Your tables have difficult names
You want to use another schema's tables
the alias Annual Salary for the calculated SELECT id, name AS "Name", salary * 12 AS "Annual salary" FROM
employee;
SELECT id, name "Name", salary * 12 "Annual salary" FROM employee;
SELECT id, name "Name", salary * 12 as Annual salary FROM employee;
INSERT INTO (SELECT * FROM employees WHERE department_id IN (20,50) WITH CHECK
OPTION)VALUES
(emp_id_seq.NEXTVAL, '&ename', '&jobid', 2000, NULL, &did);
SELECT LPAD(salary,10,*) has a salary of 17000, return *****17000 , For number (10,2)****170.00
TO_DATE function
convert any date literal to a date
format 'January 10 1999' for input
2
MERGE INTO ,We should not use table name in the update set clause and also we should not use table names in insert
values() of merge into statement.
OrderBy GroupBy
default behavior of the ORDER BY clause ASC
Date values are displayed with the earliest Date first .
Numeric values are displayed with the lowest values first.
Null value will be at last if it is asc order.
Null value will be at beginning at desc order
Column alias names can not be used in Group by clause,But can be used in Order By clause , otherwise gives an
error.
Select empname en ,empno no ,max(sal) maxsal from emp
Group by en,order by maxsal.—Error
Select * from emp where dept in (select dept from valid_dept where dept_head='soni' order by dept); Oracle returns
error cause order by can not be used in subquery,But group by can be used insub query.
ex: SELECT last_name
FROM employees
WHERE salary IN (SELECT MAX(salary)
FROM employees
GROUP BY department_id);syntax is correct
Select farm_name,cow_name
Count(carton) as number
From cowmilk
Group by cow_name;
Oracle returns error cause Non_group columns in the select statements should come left to the group columns and
should be mensioned in the grop by clause otherwise oracle returns an error.
• To remove redundancy of group by clause excution by using "With "clause can be done.
VIEWS
For adding forth column for already existing view with 3column then
CREATE OR REPLACE VIEW emp_dept_vu AS
SELECT employee_id, employee_name
Department_name, manager_id
FROM employees e, departments d
WHERE department_id = d.department_id;
Only job alter view can perform is recompiling an invalid viewALTER VIEW EMP_DEPT_VW COMPILE:
Views
A view can be created as read only
3
A view can be created as a join on two or more tables.
Can not update,delete,insert data in a view with group functions and distinct
Can not modify data of a column in a view with single row functions and functions with pseudo column.Other
columns can be modified
We can delete the data in a view if this view is not having all columns in the original table also.
If we have filter criteria in a view then we have to use check option for that …for users not to enter the values other
than the filter option…otherwise oracle gives error….or oracle gives simply 0 rows were inserted.
What does the FORCE option for creating a view do? creates a view regardless of whether or not the base tables
exist
CREATE VIEW emp_vu AS SELECT * FROM employees WHERE department_id IN (10,20) WITH CHECK
OPTION;With check option ,user cannot modify view but he can manipulate data for a view for updatable columns
of key preserved tables.
.
COMPLEX VIEWS
For complex views we cannot update any columns for two tables if they are not connected by PK and FK relation
To obtain the defination of a view Query the USER_VIEWS data dictionary view to search for the EMP_DEPT_VU
view
In order to identify any objects that may be asociated with that table and primary key dictionary view used is
USER_INDEXES
USER_CONS_COLUMNS, view should a user query to display the columns associated with the constraints on a
table owned by the user
Position of each column in a table we can know by using USER_TAB_COLUMNS, Just like DESCRIBE
USER_UPDATABLE_COLUMNS can tell whether the columns in a complex view can be modified or not.
Constraints
• constraints
Constraints can be created after the table is created
Constraints can be created at the same time the table is created
use of constraints
constraints enforce rules at the view level.
constraints enforce rules at the table level
constraints prevent the deletion of a table if there are dependencies
Check Constraint can not contain a reference to another table.check (select ID from dept)....these are not valid. and
also check constraint will not reference to virtual column like:USERS,ROWID,SYSDATE...etc.
• Check constarint correctone is ,it chould contain some set of fixed values,but not the not null values.
Aggregate functions
Count, Minimum,Maximum Aggregate functions are used on the column of datatype DATE
aggregate functions
You can mix single row columns with aggregate functions in the column list of a SELECT statement by grouping on
the single row columns.
You can pass column names, expressions, constants, or functions as parameters to an aggregate function
• Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are
commonly used with the GROUP BY clause in a SELECT statement
SubQuery
• A single row subquery can retrieve data from more than one table.
• A SQL query statement cannot display data from table B that is referred to in its subquery, unless table B is included
in the main query's FROM clause.
• Subqueries are used with the SELECT, INSERT, UPDATE, and DELETE statements.
• A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the
subquery to compare its selected columns.
• An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY can
be used to perform the same function as the ORDER BY in a subquery.
• Subqueries that return more than one row can only be used with multiple value operators, such as the IN operator.
• The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
• A subquery cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a subquery; however, the BETWEEN can be used within the subquery
• WE can query upto 255 subqueries
SubQueries
A single row subquery can retrieve only one row but many columns
A multiple row subquery can retrieve multiple rows and multiple columns
A single row subquery can use the IN operator
6
Subqueries
A subquery can retrieve zero or more rows.
When a subquery is used with an inequality comparison operator in the outer SQL statement, the column list
in the SELECT clause of the subquery should contain only one column.
SELECT *
FROM orders
WHERE cust_id = (SELECT cust_id
FROM customers
WHERE cust_name = 'Smith')
The query fails because the subquery returns more than one row.
• the main query fails because the multiple-row subquery cannot be used with the comparison operator.
• Need of co-rrelated sub query comes in case of "Exists" in where clause , Not in case of "IN" in where clause,
cause for "IN " in where clause we can contain set of values where as for exists we should have so-rrelated sub
query.
• Definitely subquery is reqired to create one table from another table with same structure and columns
Sequence
Sequences
You use a CURRVAL pseudo column to look at the current value just generated from a sequence,without affecting
the further values to be generated from the sequence.
You use a NEXTVAL pseudo column to obtain the next possible value from a sequence by actually retrieving the
value form the sequence
Transactions
Update,Delete,Insert Will be Roll backed,DDL (like:CREATE,ALTER,DROP) will not be roll backed.TRUNCATE
also will not be roll backed,cause data will be deleted at once.
"Save Point" is not a begining of new transaction.A transaction can have more than one "Save points".
7
At begining of transaction ,if we want to make the next coming statements should not alter database ,then we can use
"SET Transaction", we cant use "Save points" there cause it is at the begining of transaction.
Complete a transaction
* ROLLBACK TO SAVEPOINT C;
* ALTER TABLE employees SET UNUSED COLUMN sal;
CREATE USER scott IDENTIFIED by tiger; No privileges till yet even cannot connect to database,for this he needs
session privileges
JOINS
Two tables with different columns have been given and asked to calculate Tax for each employee,we can calculate
cause in tax column minsal and maxsal provided ,for each employee sal lies between these two salaries only.
Case to use a FULL OUTER JOIN when You want all unmatched data from both tables.
SELECT emp_name, department_name, city FROM employees e JOIN departments d USING (department_id) JOIN
locations l USING (location_id) WHERE salary > 10000;
is same as
SELECT emp_name, department_name, city FROM employees e, departments d, locations l WHERE
e.department_id = d.department_id AND d.location_id = l.location_id AND salary > 10000;
all the records from dept(right outer join), null values are in emp table(+)
All the records from emplyee left outer join, null values are in dept table(+)
Indexes
• If most of the values start with some values(like" "C001") ,then it is better to use "Reverse Index"rather than to use
"B Tree Index",In this case(some values start with perticular value) Cardinality for root node is low, B-Tree index
works fine for "column having Root having High cardinality".
Privileges
• If column is if "USERS" ,and Jone is selecting information for Mith,then no error comes but no data will be
displayed to Jone.
Drop user,Create session,Backup any Table are System Privileges, Where as Index is an object privilege.
• User Davids wants to access table EMPLOYEE owned by MARTIN.Public and privetae sysnonyms created by
martin would work best and also.David created synonym for martin.employee would work best.but synonym
created by david for just employee would not work because he is creating synonym in his own schema.
• When a Role has password assigned to it,then it should not be made default .But not the role given with system
privileges.
Inorder to administer that access for others ,we should use "grant update on emp to soni with grant option"
Reed gives object privillages to Mann ,Mann gives session privillages to Snow,and Reed revokes privilages from
Mann.
Ans: Able to Connects to database Reed and Snow
Able to Connects to database and Does operations on database Reed Only
Reed gives session privillages to Mann ,Mann gives session privillages to Snow,and Reed revokes privilages from
Mann.
Ans: Able to Connects to database Reed and Snow
Able to Connects to database and Does operations on database Reed and Snow
Table Spaces
For making tablespace read only , we need to make sure that
* Table space is not involved for any active rollbacks and
* Tablespace is not involved for any open backups and also
* Tablespace should be online.
Rename datafile with alter tablespace, then we should make sure of database is open and datafiles must be offline
before
renaming.
9
the following is true if you use the alter tablespace statement and specify the TEMPORARY clause (Choose all
that apply)?
A. Oracle no longer perform any checkpoint for the online datafiles in the tablespace
B. Oracle performs a checkpoint for all online datafiles in the tablespace
C. Oracle does not ensure that all files are written
D. The offline files may require media recovery before you bring the tablespace online
Tables
• DELETE employees;
The data in the EMPLOYEES table is deleted but not the structure.
• For create table we need to use CREATE TABLE not to use CREATE OR REPLACE TABLE
1
• Maximum number of columns that a table can have 1000.
• NVL
• NVL2
• CONCAT
• DECODE
• DUMP
• and REPLACE
can return non-NULL value when called with a NULL argument.
TO_DATE(s[, fmt[, nls]]) Converts string s to DATE
TO_CHAR(x[, fmt[, nls]]) Takes up to three arguments, where x is either a date or a number
four are types of functions available in SQL character ,numeric, date, conversion
• A version of SQL*PLUS which runs in a browser,Usnig browser we can connect to an isql prompt.
SQL: Manuplates data and table definitions in the database.
iSQL*PLUS: Does not allow manuplation of values in database.
http://ct.xab.ac.cn/Portals/0/Oracle%20SQL/D33053%20introduction%20to%20oracle%209i_sql%20v3.pdf
• Selection,projection,join
Select empid,empname,deptname from emp,dept where emp.deptid=dept.deptid
• Projection,selection.join
Select empid,empname,deptname from emp,dept where emp.deptid=dept.deptid and empjob=’manager’
• If users wants to give a runtime value then it is best to use accept command only
• NVL2 function displays NOT NULL values and then NULL value.
1
select empname,nvl2(joinid,'yes','no') from employee;
LOCKS
• UPDATE,SELECT,DELETE statement will acquire row_exclusive lock .
• SELECT FOR UPDATE aquires lock SHARE ROW LOCK
• SET TRANSACTION ISOLATION LEVEL READ COMMITTED. Is default
• SET TRANSACTION ISOLATION LEVEL SERIALIZABLE is defined in SQL92
• SQLPLUS commands
• Describe
• List
SP-0023 No lines in sqlbuffer
• Del 3
• Append ‘soni’
• Clear buffer
• Input
• Run
• 6 ‘new line being added’
• Spool ctrl.out
Select * from emo;
Spool off
Save ctrlprod.sql
Exit
Afiedt.buf buffer
• OrderBy Group By
• Single Row functions
o Text functions:Rpad,Lpad,Initcap,Lower,Upper,length,Substr,Instr
o Arithemetic functions:Abs,Ceil,Floor,Mod,Round,Sqrt,Trunc,sinh()
o List functions: greatest,least,Decode,
Date functions:months_between,add_months,next_day,last_day,new_time
Conversion functions:To_char,To_date,To_number
1
JOINS
Cartesian join
Natural join: used with filter condition
Left outer join
Right outer join
Self join
• Group Functions
• Avg(),sum(),count(),min(),max(),stddev(),variance()
• Using group by clause-Rollup and Cube
• Using group by and having
Sub Quries
Single row subqueries
Multi row subqueries.Multi column subqueries
Inline views
Using with clause for group by
• Readable Output
• substitution variable:& and set define ?
• lexical substitution variable:&&
• Automatic difination at runtime :define and undefine:reuse substitution variable bypassing value
from one statement to other.
• Accept Prompt:when you want more accurate and explicit datatype conversion :accept allows only
string information to be accepted by user
SQLPLUS COMMANDS
• Feedback,
• break on deptno:Will make duplicate values not to display in deptno:clear breaks
• compute sum of sal on deptno :calculate sum of sal in each dept depending on deptno:clear computes
• column sal format $9999.99,
• btitle
• ttitle
• linesize
• pagesize
• Array size
• Auto trace
• Set pagesize
• Set termout on/off
• Store(we use save in sql)
Store set myfile.out
Save myfile.out
Views
Privileges
Locks