You are on page 1of 61

EXTRACT function

EXRACT returns value of a specified date time field from a date time or interval value.
SELECT EXTRACT (YEAR FROM SYSDATE ) FROM dual;
SELECT ename ,hire date ETRACT (MONTH FROM HIREDATE) FROM emp WHERE mgr=100

STRING to TIMESTAMP convertion

Display the character ,2008-08-25 11:00:00 as TIMESTAMP value

SELECT TO_TIMESTAMP(2008-08-25 11:00:00,YYYYMM-DD HH:MI:SS) FROM DUAL;

Display the character ,2008-08-25 11:00:00 8:00 as TIMESTAMP WITH TIME ZONE

SELECT TO_TIMESTAMP_TZ(2008-08-25 11:00:00 8:00,YYYY-MM-DD HH:MI:SS TZH:TZM) FROM DUAL

Time Interval Conversion with TO_YMINTERVAL


Display a date that is one year 2 months after the hiredate for the employees working in the department with the deptno 20 SELECT hiredate, hiredate+TO_YMINTERVAL(01-02)AS HIRE_date_YMINTERVAL FROM emp WHERE deptno=20;

DATE Datatype

The DATE datatype stores date and time information Oracle stores the following information: century, year, month, date, hour, minute, and second. The default date format for an Oracle date value is specified by the initialization parameter NLS_DATE_FORMAT. Date format includes a two-digit number for the day of the month, an abbreviation of the month name, the last two digits of the year, and a 24hour time designation.
4

The Julian equivalent of January 1, 2011


SELECT TO_CHAR(TO_DATE('01-012011', 'MM-DD-YYYY'),'J') FROM DUAL;
TO_CHAR --------

TIMEZONES

Display the time zone offset for the time zone US/Eastern
SELECT TZ_OFFSET(US/Eastern) FROM dual

Display current date and time in the sessions time zone

ALTER SESSION SET NLS_DATE_FORMAT=DD-MON-YYYY HH24:MI:SS:


ALTER SESSION SET TIME_ZONE=-8:0;

CURRENT_DATE is sensitive to the session time zone.


6

SELECT SESSIONTIMEZONE ,CURRENT_DATE FROM dual; SELECT SESSIONTIMEZONE , CURRENT_TIMESTAMP FROM dual; SELECT CURRENT_TIMESTAMP , LOCALTIMESTAMP FROM dual;

(CURRENT_TIMESTAMP returns TIMESTAMP WITH TIME ZONE value and LOCALTIMESTAMP returns TIMESTAMP values
7

CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP

CURRENT_DATE

Returns the current date from the system Has a data type of DATE Returns the current timestamp from the system Has a data type of TIMESTAMP WITH TIME ZONE Returns the current timestamp from user session Has a data type of TIMESTAMP
8 8

CURRENT_TIMESTAMP

LOCALTIMESTAMP

DBTIMEZONE and SESSIONTIMEZONE

Display the value of the database time zone.


SELECT DBTIMEZONE FROM DUAL;

Display the value of the sessions time zone.


SELECT SESSIONTIMEZONE FROM DUAL;

TIMESTAMP Data Type

The TIMESTAMP data type is an extension of the DATE data type. It stores the year, month, and day of the DATE data type, plus hour, minute, and second values, as well as the fractional second value. Variations in TIMESTAMP are:

TIMESTAMP TIMESTAMP

[(fractional_seconds_precision)]_ [(fractional_seconds_precision)]_ WITH

TIME ZONE TIMESTAMP

[(fractional_seconds_precision)]_ WITH
LOCAL TIME ZONE
10 10

TIMESTAMP Data Types


Data Type Fields Year, Month, Day, Hour, Minute, Second with fractional seconds Same as the TIMESTAMP data type; also includes: TimeZone_Hour, and TimeZone_Minute or TimeZone_Region TIMESTAMP WITH LOCAL TIME ZONE Same as the TIMESTAMP data type; also includes a a time zone offset in its value
11 11

TIMESTAMP TIMESTAMP WITH TIME ZONE

TIMESTAMP Fields

Datetime Field YEAR

Valid Values 4712 to 9999 (excluding year 0)

MONTH
DAY HOUR MINUTE SECOND TIMEZONE_HOUR

01 to 12
01 to 31 00 to 23 00 to 59 00 to 59.9(N) where 9(N) is precision 12 to 14

TIMEZONE_MINUTE

00 to 59

12 12

Difference between DATE and A B TIMESTAMP


-- when hire_date is of type DATE SELECT hire_date FROM emp5; ALTER TABLE emp5 MODIFY hire_date TIMESTAMP; SELECT hire_date FROM emp5;


13 13

TIMESTAMP WITH TIME ZONE Data Type

TIMESTAMP WITH TIME ZONE is a variant of TIMESTAMP that includes a time zone displacement in its value. The time zone displacement is the difference, in hours and minutes, between local time and UTC. TIMESTAMP[(fractional_seconds_precision)] It is specified as:
WITH TIME ZONE

14 14

TIMESTAMP WITH TIMEZONE: Example


CREATE TABLE web_orders (ord_id number primary key, order_date TIMESTAMP WITH TIME ZONE); INSERT INTO web_orders values (ord_seq.nextval, current_date); SELECT * FROM web_orders;

15 15

TIMESTAMP WITH LOCAL TIMEZONE


TIMESTAMP WITH LOCAL TIME ZONE is another variant of TIMESTAMP that includes a time zone displacement in its value. Data stored in the database is normalized to the database time zone. The time zone displacement is not stored as part of the column data. The Oracle database returns the data in the users local session time zone. The TIMESTAMP WITH LOCAL TIME ZONE data type is specified as follows: TIMESTAMP[(fractional_seconds_precision)] WITH LOCAL TIME ZONE
16 16

TIMESTAMP WITH LOCAL TIMEZONE: Example


CREATE TABLE shipping (delivery_time TIMESTAMP WITH LOCAL TIME ZONE); INSERT INTO shipping VALUES(current_timestamp + 2); SELECT * FROM shipping;

ALTER SESSION SET TIME_ZONE = 'EUROPE/LONDON';

SELECT * FROM shipping;

17 17

INTERVAL Data Types

INTERVAL data types are used to store the difference between two datetime values. There are two classes of intervals:

Year-month Day-time
The actual subset of fields that constitutes an interval Specified in the interval qualifier
Fields Year, Month Days, Hour, Minute, Second with fractional seconds
18 18

The precision of the interval is:


Data Type INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND

INTERVAL Fields
INTERVAL Field
YEAR MONTH

Valid Values for Interval


Any positive or negative integer 00 to 11

DAY
HOUR MINUTE SECOND

Any positive or negative integer


00 to 23 00 to 59 00 to 59.9(N) where 9(N) is precision

19 19

INTERVAL YEAR TO MONTH Data Type

INTERVAL YEAR TO MONTH stores a period of time using the YEAR and MONTH datetime fields.
For example:
INTERVAL YEAR [(year_precision)] TO MONTH '312-2' assigned to INTERVAL YEAR(3) TO MONTH

Indicates an interval of 312 years and 2 months


'312-0' assigned to INTERVAL YEAR(3) TO MONTH Indicates 312 years and 0 months

'0-3' assigned to INTERVAL YEAR TO MONTH


Indicates an interval of 3 months

20 20

INTERVAL YEAR TO MONTH: Example


CREATE TABLE T_EG( LOAN_DURATION INTERVAL YEAR(3)TO MONTH); INSERT INTO T_EG VALUES(INTERVAL 120MONTHS(3));

SELECT TO_CHAR(SYSDTE+LOAN_DURATION,DD-MON-YYYY) FROM T_EG;

21 21

INTERVAL DAY TO SECOND (fractional_seconds_precision)st ores a period of time in days, hours, minutes, and seconds.
INTERVAL DAY[(day_precision)] For example:
TO Second INTERVAL '6 03:30:16' DAY TO SECOND

INTERVAL DAY TO SECOND Data Type

Indicates an interval of 6 days 3 hours 30 minutes and 16 seconds


INTERVAL '6 00:00:00' DAY TO SECOND Indicates an interval of 6 days and 0 hours, minutes and 0 seconds 0

22 22

INTERVAL DAY TO SECOND Data Type: Example


CREATE TABLE T_EG1 ( DAY_DURATION INTERVAL DAY(3) TO SECOND); INSERT INTO T_EG1 VALUES (INTERVAL 180DAY(3));

SELECT SYSDATE+DAY_DURATIONhalf year

FROM T_EG1;

23 23

EXTRACT

Display the YEAR component from the SELECT EXTRACT (YEAR FROM SYSDATE) FROM DUAL; SYSDATE.

SELECT last_name, hire_date, Display the MONTH FROM HIRE_DATE) EXTRACT (MONTH component from the FROM employees for those employees whose HIRE_DATE WHERE manager_id = 100;

MANAGER_ID is 100.

24

TZ_OFFSET

Display the time zone offset for the time zone


'US/Eastern'.
SELECT TZ_OFFSET('US/Eastern') FROM DUAL;

Display the time zone offset for the time zone


'Canada/Yukon'.
SELECT TZ_OFFSET('Canada/Yukon') FROM DUAL;

Display the time zone offset for the time zone


'Europe/London'.
SELECT TZ_OFFSET('Europe/London') FROM DUAL;

25

Using TO_DSINTERVAL: Example

TO_DSINTERVAL: Converts a character string to an INTERVAL DAY TO SECOND data type


SELECT last_name, TO_CHAR(hire_date, 'mm-dd-yy:hh:mi:ss') hire_date, TO_CHAR(hire_date + TO_DSINTERVAL('100 10:00:00'), 'mm-dd-yy:hh:mi:ss') hiredate2 FROM employees;

26 26

Daylight Saving Time

First Sunday in April


Time jumps from 01:59:59 a.m. to 03:00:00 a.m. Values from 02:00:00 a.m. to 02:59:59 a.m. are not valid. Time jumps from 02:00:00 a.m. to 01:00:01 a.m. Values from 01:00:01 a.m. to 02:00:00 a.m. are ambiguous because they are visited twice.

Last Sunday in October


27 27

The RR Datetime Format


The RR datetime format element is similar to the YY datetime format element In addition it provides flexibility for storing date values in other centuries. The RR datetime format element lets you store 20th century dates in the 21st century by specifying only the last two digits of the year.

28

YY vs RR Format
SELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MONRR') ,'YYYY') "Year FROM DUAL; Year ---1998 SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MONRR') ,'YYYY') "Year FROM DUAL; Year ---2017
29

Synonyms, Indexes and Sequences

30

Database Objects
Object Table Description Basic unit of storage; composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object

View

Sequence Index Synonym

31

What Is a Sequence?

Automatically generates unique numbers Is a sharable object Is typically used to create a primary key value Replaces application code Speeds up the efficiency of accessing sequence values when cached in memory

32

Creating a Sequence
Define

a sequence to generate sequential numbers automatically


CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}];

33

Creating a Sequence

Create a sequence named DEPT_DEPTNO to be used for the primary key of the DEPARTMENT table. Do not use the CYCLE option.
SQL> CREATE SEQUENCE dept_deptno 2 INCREMENT BY 1 3 START WITH 91 4 MAXVALUE 100 5 NOCACHE 6 NOCYCLE; Sequence created.

34

Confirming Sequences

Verify your sequence values in the USER_SEQUENCES data dictionary table.


sequence_name, min_value, max_value, increment_by, last_number user_sequences;

SQL> SELECT 2 3 FROM

The LAST_NUMBER column displays the next available sequence number.


35

Pseudo columns

NEXTVAL returns the next available sequence value. CURRVAL obtains the current sequence value. ROWID uniquely identify the rows in your table. LEVEL a special column you can reference only in a hierarchical query

36

Using a Sequence

Insert a new department named MARKETING in San Diego.


departmnent(deptno, dname, loc) (dept_deptno.NEXTVAL, 'MARKETING', 'SAN DIEGO');

SQL> INSERT INTO 2 VALUES 3 1 row created.

SQL> SELECT 2 FROM

View the current value for the DEPT_DEPTNO sequence.


dept_deptno.CURRVAL dual;

37

Using a Sequence

Caching sequence values in memory allows faster access to those values. Gaps in sequence values can occur when:

A rollback occurs The system crashes A sequence is used in another table

View the next available sequence, if it was created with NOCACHE, by querying the USER_SEQUENCES table.
38

Modifying a Sequence
Change

the increment value, maximum value, minimum value, cycle option, or cache option.
SQL> ALTER SEQUENCE dept_deptno 2 INCREMENT BY 1 3 MAXVALUE 999999 4 NOCACHE 5 NOCYCLE; Sequence altered.

39

Removing a Sequence

Remove a sequence from the data dictionary by using the DROP SEQUENCE statement. Once removed, the sequence can no longer be referenced.

SQL> DROP SEQUENCE dept_deptno; Sequence dropped.

40

What Is an Index?

Schema object Used by the Oracle Server to speed up the retrieval of rows by using a pointer Reduces disk I/O by using rapid path access method to locate the data quickly Independent of the table it indexes Automatically used and maintained by the Oracle Server
41

How Are Indexes Created?

Automatically

A unique index is created automatically when you define a PRIMARY KEY or UNIQUE key constraint in a table definition.

Manually

Users can create nonunique indexes on columns to speed up access time to the rows.

42

Creating an Index

Create an index on one or more columns

CREATE INDEX index ON table (column[, column]...);

Improve the speed of query access on the ENAME column in the EMP table
emp_ename_idx employee(ename);

SQL> CREATE INDEX 2 ON Index created.

43

Confirming Indexes

The USER_INDEXES data dictionary view contains the name of the index and its uniqueness. The USER_IND_COLUMNS view contains the index name, the table name, and the column name.
SELECT FROM WHERE AND

SQL> 2 3 4 5

ic.index_name, ic.column_name, ic.column_position col_pos,ix.uniqueness user_indexes ix, user_ind_columns ic ic.index_name = ix.index_name ic.table_name = 'EMP';

44

Removing an Index

Remove an index from the data dictionary.

SQL> DROP INDEX index;

Remove the EMP_ENAME_IDX index from the data dictionary.

SQL> DROP INDEX emp_ename_idx; Index dropped.

To drop an index, you must be the owner of 45 the index or have the DROP ANY INDEX

STRUCTURE OF INDEXES
B-TREE:High cardinality,updateson keys relatively inexpensive,inefficient for queries using OR predicates,Useful for OLTP BITMAP:Low cardinality columns,Updates to key columns very expensive,Efficient for queries using OR operator,Useful in datawarehousing

46

Synonyms

47

Synonyms
Create a synonym.

SQL> CREATE SYNONYM d_sum 2 FOR dept_sum_vu; Synonym Created.

Drop a synonym.
SQL> DROP SYNONYM d_sum; Synonym dropped.

48

Synonyms
Simplify

access to objects by creating a synonym (another name for an object).


Refer to a table owned by another user. Shorten lengthy object names.

CREATE [PUBLIC] SYNONYM synonym FOR object;

49

Create & Remove Synonyms

Create a shortened name for the DEPT_SUM_VU view.

SQL> CREATE SYNONYM d_sum 2 FOR dept_sum_vu; Synonym Created.

Drop a synonym.
SQL> DROP SYNONYM d_sum; Synonym dropped.

50

USING SQL*PLUS

51

Viewing Structure of Table Editing SQL Statements Command Description A[PPEND] text Appends text to the current line. C[HANGE] /old/new Changes the text specified by old to new in the current line CL[EAR] BUFF[ER] Clears all lines from the buffer. DEL Deletes the current line. DEL x Deletes the line specified by the line number x (line numbers start with 1) L[IST] Lists all the lines in the buffer. L[IST] x Lists line number x. R[UN]or/ Runs the statement stored in the buffer. You can also use / to run the statement.x Makes the line specified by the line number x the current line.

52

SQL> SELECT empid, first_name, last_name 2 FROM emp 3 WHERE empid = 100;

SQL> 1 SQL> APPEND , dob SQL> LIST SQL> CHANGE /empid = 100/empid = 200 SQL> RUN SQL> / SQL> SPOOL OFF
53

SQL> SELECT empid, first_name, last_name 2 FROM emp 3 WHERE empid = 100;

SQL> SAVE emp_query.sql SQL> GET emp_query.sql SQL> START emp_query.sql SQL> EDIT SQL> SPOOL emp_results.txt SQL> /
54

Setting the Page Size SQL> SET PAGESIZE 100 SQL> / Note The maximum number for the page size is 50,000. Setting the Line Size SQL> SET LINESIZE 50 SQL> SELECT * FROM emp; Note The maximum number for the line size is 32,767.
55

Clearing Column Formatting SQL> COLUMN product_id CLEAR SQL> CLEAR COLUMNS Controlling Output Lines SQL> SET VERIFY OFF SQL> SET VERIFY ON Changing the Variable Definition Character SET DEFINE '#' SQL> SELECT product_id, name, price 2 FROM products 3 WHERE product_id = #product_id_var;
56

SQL> DEFINE deptid = 60 ACCEPT hiredate DATE FORMAT 'DDMON-YYYY' PROMPT 'Date: Date: 12-DEC-2006 SQL> DEFINE Notice that hiredate is stored as a CHAR SQL> ACCEPT password_var CHAR PROMPT 'Password: ' HIDE Password: ******* SQL> UNDEFINE deptno SQL> UNDEFINE hiredate SQL> UNDEFINE password_var 57

Substitute variable
Used for Temporarily store values As & or && or define command Example Select empid,&colname From &tbname where &condiion Note:cannot be used as the first word at the first word entered at the cmd prompt

58

DEFINE variable=value UNDEFINE to clear it.

59

Sample report

Ttitle Employee |Report Btitle Confidential Break on job-id Column job_id Heading Job|Category Column sal Heading Salary Format $99,999.00 Column lname Heading Employees Select job_id,sal,lname from emp where sal<15000 Order by job_id,lname /
60

Column job_id clear Column lname clear Column sal clear Clear break

61

You might also like