Professional Documents
Culture Documents
Oracle
Oracle
Oracle
com/technetwork/issue-archive/2012/12-
may/o32sql-1541432.html
Rename:-
Select Col1 as new from table name….or select Col1 new from table name.
SELECT last_name AS name, commission_pct comm.
Distinct:-
Distinct will display the whole row as distinct.
Select distinct cola, colb, colc from table name.
You also cannot specify DISTINCT if the SELECT list contains LOB columns.
Describe command:-
Desc[ribe] table name
It describes the following things:-
Column name, null or not, data type.
Like command:-
% for zero or many char
_ for exactly one char
You can use escape identifier to search for actual % and _
Like %hello!% escape ! will return hello%, bhello% and soon..
[abc] will search either for a or b or c
[!abc] will search all letter except a,b,c
Order by:-
When distinct keyword is used in select, order by list contains only those columns which are
there in select list.
When an ORDER BY clause sorts results in ascending order, any null values are displayed last by
default. Conversely, if an ORDER BY clause specifies descending order for a column containing
null values, as in Listing 7, the null values are displayed first by default. By using the NULLS
FIRST or NULLS LAST option in the ORDER BY clause, you can override the defaults and explicitly
specify how you want null values to be sorted. The example in Listing 8 uses the NULLS FIRST
option to override the default display-nulls-last behavior of an ORDER BY clause
SQL> select employee_id, first_name, last_name, manager
2 from employee
3 ORDER BY manager NULLS FIRST, last_name;
If start_position is 0, then substr treats start_position as 1 (ie: the first position in the string).
If start_position is a positive number, then substr starts from the beginning of the string.
If start_position is a negative number, then substr starts from the end of the string and counts
backwards.
INSTR function: - In Oracle/PLSQL, the instr function returns the location of a substring in a
string.
start_position is the position in string1 where the search will start. This argument is optional. If
omitted, it defaults to 1. The first position in the string is 1. If the start_position is negative, the
function counts back start_position number of characters from the end of string1 and then
searches towards the beginning of string1
If string2 is not found in string1, then the instr Oracle function will return 0.
Number functions:-
ROUND (45.923,-1) = 50
FROM DUAL;
FROM DUAL
Date:-
Date Functions
MONTHS_BETWEEN returns number of months between dates date1 and date2. If date1 is
later than date2, then the result is positive. If date1 is earlier than date2, then the result is
negative. If date1 and date2 are either the same days of the month or both last days of months,
then the result is always an integer
SHOW money
94,567.00
nlsparams
A text expression that specifies the thousands group marker, decimal marker, and currency
symbols used in text-exp. This expression contains one or more of the following parameters,
separated by commas:
NLS_CURRENCY symbol
NLS_ISO_CURRENCY territory
NLS_NUMERIC_CHARACTERS dg
symbol
A text expression that specifies the local currency symbol. It can be no more than 10 characters.
territory
A text expression that identifies the territory whose ISO currency symbol is used.
dg
A text expression composed of two different, single-byte characters for the decimal marker (d)
and thousands group marker (g).
NVL(expr1, expr2)
Coalesce(expr1,expr2,expr3,expr4....)
CASE expression
DECODE function
[, search2, result2,...,]
[, default])
Group functions:-
Functions that operate on group of rows are called group functions
AVG
• COUNT
• MAX
• MIN
• STDDEV
• SUM
• VARIANCE
Count(*) return the no. of rows in a table
COUNT(expr) returns the number of rows with non-null values for the expr.
Group functions ignore null values in the column.
The NVL function forces group functions to include null values. Copyright © Oracle
Corporation, 2001. All rights reserved.
SELECT AVG(NVL(commission_pct, 0))
FROM employees;
Group by:-
All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.
The GROUP BY column does not have to be in the SELECT list.
You can group by more than one coloumn:
Subqueries:-
Single row sub query: - use single row operator like =, <, > sub query returns only one value on
which this operator operates on.
Multiple row sub query:- return multiple values and IN,ANY and ALL operator operates on them
The "WITH CHECK OPTION" is used to indicate that Oracle will prevent any changes to
the table or view that would produce rows that are not included in the subquery.
One of the ways to validate data while insertion, directly at the database level is :
INSERT …. WITH CHECK OPTION
Schema : Scott
Let’s create a test table from the standard “emp” table and work on it.
Hence forth, in Department 30 manager’s should have commission between 750 – 1000
(included).
select *
from test_emp e
where e.deptno = 30
and e.job = 'MANAGER'
and e.comm >= 750
and e.comm <= 1000;
Usually the developers take care of this validation on the front-end itself. If there is only
one point of data entry to your database (Eg : Web front-end), it’s okay to validate at
the entry point. But think of a situation where there are multiple point of data entries to
your database (Eg : Web front-end, Feeds, Web Services, JMS, MDB’s …etc.,).
So,
a) You have to duplicate the validation (it is almost impossible to maintain a common
code base between these many discrete systems. Even if you have a common code
base, on system might just not invoke the validation at all.)
b) If a common code base for validations is not used, then there could be a bug or
missing implementation in any of the systems.
So, how about having a validation just before inserting the data into the database ?
PL/SQL strikes immediately right
We can put the volition logic in a pl/sql procedure/function and let all the above
discrete systems invoke it.
But…….. there is a performance overhead. We are adding another layer after data access
layer. For simple/moderate systems, it is okay. What we have a high volume system.
Oracle prohibits any changes to the table or view that would produce the rows that are
not included in the sub query.
Make the above select query as a sub query to insert() as shown below.
insert into
(select *
from test_emp e
where e.deptno = 30
and e.job = 'MANAGER'
and e.comm >= 750
and e.comm <= 1000) values (7935, 'New Guy', 'MANAGER', 7782, sysdate, 1600.00,
500, 30);
The data that we are trying to insert in this query is against our rules, as the commission
is = 500.
If you execute the above insert, Oracle still inserts the record.
insert into
(select *
from test_emp e
where e.deptno = 30
and e.job = 'MANAGER'
and e.comm >= 750
and e.comm <= 1000 with check option)
values
(7935, 'New Guy', 'MANAGER', 7782, sysdate, 1600.00, 500, 30);
When you try to execute the above insert, you will get an error message :
So, no matter where the data is coming from, we could perform a validation directly on
the insert itself.
Also, note that we are NOT performing an extra query, as the sub query is within the
insert itself.
Merge :-
Provides the ability to conditionally update or insert data into a database table
Performs an UPDATE if the row exists, and an INSERT if it is a new row:
Constraint
Constraint enforce the rules which should be met while inserting, deleting or updating a table
Constraint types are:-
Primary Key
Foreign Key
Unique
Not Null
Check
Name a constraint or the Oracle server generates a name by using the SYS_Cn format.
Create a constraint either:
– At the same time as the table is created, or
– After the table has been created
Define a constraint at the column or table level.
Table level for ex:- when primary key consists of two column then it should be defined at the
table level
REFERENCES departments(department_id),
ON DELETE CASCADE: Deletes the dependent rows in the child table when a row in the parent
table is deleted.
ON DELETE SET NULL: Converts dependent foreign key values to null
The basic differences between Primary Key and Unique key are as follows.
3) A table can have only one PK but It can have any number of UNIQUE Key.