Oracle

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

http://www.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.

 Requires double quotation marks if it contains spaces or special characters or is


case sensitive

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;

EMPLOYEE_ID FIRST_NAME LAST_NAME MANAGER


——————————— —————————————— ———————————— ——————————
28 Emily Eckhardt
37 Frances Newton
6567 Roger Friedli 28
6568 Betsy James 28
7895 Matthew Michaels 28
1234 Donald Newton 28

Case manipulation function:-


These functions convert case for character strings.

LOWER ('SQL Course') sql course

UPPER ('SQL Course') SQL COURSE

INITCAP ('SQL Course') Sql Course

Character manipulation function:-


CONCAT function: - concat can only concat two strings, you have to use nested concat function
to concat more than two strings.

SUBSTR function: - The syntax for the SUBSTR function is:


SUBSTR (string, start_position, [length]) length is optional. It is the number of characters to extract. If
this parameter is omitted, substr will return the entire string.

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.

If length is a negative number, then substr will return a NULL value

Length function: - return the length of the string

INSTR function: - In Oracle/PLSQL, the instr function returns the location of a substring in a
string.

The syntax for the instr Oracle function is:

Instr ( string1, string2 [, start_position [, nth_appearance ] ] )

String1 is the string to search.

String2 is the substring to search for in string1.

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

nth_appearance is the nth appearance of string2. This is optional. If omitted, it defaults to 1.

If string2 is not found in string1, then the instr Oracle function will return 0.

Number functions:-

Round: - SELECT ROUND (45.923, 2) = 45.92, ROUND (45.923, 0) = 46,

ROUND (45.923,-1) = 50

FROM DUAL;

Trunc: - SELECT TRUNC (45.923, 2) = 45.92, TRUNC (45.923) = 45,


TRUNC (45.923,-2) = 0

FROM DUAL

MOD: - gives the Remainder

Date:-

 The default date display format is DD-MON-RR.


 Sysdate is a function that return date and time.
 Add or subtract a number to or from a date for a resultant date value.
 Subtract two dates to find the number of daysbetween those dates.
 Add hours to a date by dividing the number of hours by 24.

Date Functions

 MONTHS_BETWEEN:- Number of months between two dates

MONTHS_BETWEEN ('01-SEP-95','11-JAN-94') → 19.6774194.


Months_between (date1, date2) = date1-date2

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

• ADD_MONTHS ('11-JAN-94', 6) = Add calendar months to


Date = 11-JUL-94

 NEXT_DAY ('01-SEP-95','FRIDAY') = Next day of the date specified = 08-SEP-95


 LAST_DAY('01-FEB-95') = Last day of the month = ‘28-FEB-95'

Assume SYSDATE = '25-JUL-95':


 ROUND(SYSDATE,'MONTH') 01-AUG-95
 ROUND(SYSDATE ,'YEAR') 01-JAN-96
 TRUNC(SYSDATE ,'MONTH') 01-JUL-95
 TRUNC(SYSDATE ,'YEAR') 01-JAN-95

Explicit Data conversion:-


To_Number (Charachter) =

to_number('1210.73') would return the number 1210.73

money = TO_NUMBER('$94 567,00', 'L999G999D00', NLS_NUMERIC_CHARACTERS ', ')

SHOW money

The output of this statement is:

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).

These parameters override the default values specified by the NLS_CURRENCY,


NLS_ISO_CURRENCY, and NLS_NUMERIC_CHARACTERS options. Refer to NLS Options for
additional information
Functions that operate on null values:-

NVL(expr1, expr2)

NVL2(expr1,expr2,expr3) if null expr3 else expr2

NULLIF(expr1,exp2) if (exp1=expr2) return null else return expr1

Coalesce(expr1,expr2,expr3,expr4....)

If then else logic is represented in oracle by two means:-

 CASE expression
 DECODE function

CASE expr|col WHEN comparison_expr1 THEN return_expr1

[WHEN comparison_expr2 THEN return_expr2

WHEN comparison_exprn THEN return_exprn

ELSE else_expr] END

DECODE(col|expression, search1, result1

[, 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:

SELECT department_id dept_id, job_id, SUM(salary)


FROM employees
GROUP BY department_id, job_id ;

 You cannot use the WHERE clause to restrict groups.


 You use the HAVING clause to restrict groups.
 You cannot use group functions in the WHERE clause.
First where is calculated then group functions and group by ,having etc...

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

Variable substitution in SQL:-


 & prompts the user for a value, may use in (select, where and order by)
 Define define a variable which we may use in sql query, undefine undefined the previously
defined variable

DEFINE employee_num = 200

SELECT employee_id, last_name, salary, department_id


FROM employees
WHERE employee_id = &employee_num ;
 && Use the double-ampersand (&&) if you want to reuse the variable value without
prompting the user each time.

SELECT employee_id, last_name, job_id, &&column_name


FROM employees
ORDER BY &column_name;

With Check Option:-

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.

--The following statement is legal even though


-- the third value inserted violates the condition
-- of the subquery where_clause:
 
INSERT INTO (SELECT department_id, department_name, location_id
FROM departments WHERE location_id < 2000)
VALUES (9999, 'Entertainment', 2500);
 
 
-- However, the following statement is illegal because it contains
-- the WITH CHECK OPTION clause:
 
INSERT INTO (SELECT department_id, department_name, location_id
FROM departments WHERE location_id < 2000 WITH CHECK OPTION)
VALUES (9999, 'Entertainment', 2500);
*
ERROR at line 2:
ORA-01402: VIEW WITH CHECK OPTION where-clause violation
Insert with check option

One of the ways to validate data while insertion, directly at the database level is :
INSERT …. WITH CHECK OPTION

Let’s take an example and see what it is.

Database version : Oracle 10g.

Schema : Scott

Let’s create a test table from the standard “emp” table and work on it.

create table test_emp as select * from emp;

Let us suppose that our requirement is something like this :

Hence forth, in Department 30 manager’s should have commission between 750 – 1000
(included).

For our requirement above, the select query would be :

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 “almost always” has an option.

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.

select * from test_emp e where e.empno = 7935;

1 7935 New Guy MANAGER 7782 5/29/2008 9:02:05 AM 1600.00 500.00 30

Provide “WITH CHECK OPTION” in the sub query 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 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 :

ORA-01402 : view WITH CHECK OPTION where-clause violation

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:

MERGE INTO table_name table_alias


USING (table|view|sub_query) alias
ON (join condition)
WHEN MATCHED THEN
UPDATE SET
col1 = col_val1,
col2 = col2_val
WHEN NOT MATCHED THEN
INSERT (column_list)
VALUES (column_values

Insert or update rows in the COPY_EMP table to match


the EMPLOYEES table.

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.department_id = e.department_id
WHEN NOT MATCHED THEN
INSERT VALUES(e.employee_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);

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

See slide 348 and 347 to define the constraint

Foreign Key Constraint:-


CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)

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.

1) By default Primary Key will generate Clustured Index


whereas Unique Key will Generate Non-Clustured Index.

2) Primary Key is a combination of Unique and NOT NULL Constraints so it can’t


have duplicate values or any NUll
Whereas for Oracle UNIQUE Key can have any number of NULL whereas for SQL
Server It can have only one NULL

3) A table can have only one PK but It can have any number of UNIQUE Key.

You might also like