date data type and globalization in oracle

65
https://ir.linkedin.com/in/masoud-haji-hassan-pour By: Masoud Haji Hassan Pour Date data type and Globalization in Oracle

Upload: masoud-haji-hassan-pour

Post on 03-Mar-2017

171 views

Category:

Software


1 download

TRANSCRIPT

Page 1: Date data type and Globalization in Oracle

https://ir.linkedin.com/in/masoud-haji-hassan-pour

By:Masoud Haji Hassan Pour

Date data typeand Globalizationin Oracle

Page 2: Date data type and Globalization in Oracle

Agenda

• Describe Date data type• Formatting Date data type• Arithmetic on Date data type• Single row functions• Oracle Globalization• Date consideration in flashback

Page 3: Date data type and Globalization in Oracle

Agenda

• Describe Date data type• Formatting Date data type• Arithmetic on Date data type• Single row functions• Oracle Globalization• Date consideration in flashback

Page 4: Date data type and Globalization in Oracle

Describe Date data type

SQL> select sysdate from dual;

SYSDATE---------11-FEB-17

DD-MON-RR is default format for retrieving Date data type in oracle and based on NLS_TERRITORY.

Page 5: Date data type and Globalization in Oracle

Describe Date data type

ContentCentury

YearMonthDayHour

MinuteSecond

Page 6: Date data type and Globalization in Oracle

Describe Date data typeSQL> create table test (c1 date);Table created.SQL> insert into test values(sysdate);1 row created.SQL> commit;Commit complete.SQL> select * from test;C1---------11-FEB-17SQL> select to_char(c1, 'cc yyyy-mm-dd hh24:mi:ss') as mydate from test;MYDATE----------------------21 2017-02-11 14:07:25

Page 7: Date data type and Globalization in Oracle

Describe Date data typeInserting or updating a date value in a table will implicitly use truncated month

SQL> insert into test values (sysdate);

1 row created.

SQL> insert into test values (to_date('12','mi'));

1 row created.

SQL> select to_char(c1, 'cc yyyy-mm-dd hh24:mi:ss') as mydate from test;

MYDATE----------------------21 2017-02-11 15:55:3821 2017-02-01 00:12:00

Page 8: Date data type and Globalization in Oracle

Describe Date data typeMinimum and Maximum Date value in Oracle:

January 1, 4712 BCE ~ December 31, 9999 CE

Page 9: Date data type and Globalization in Oracle

Agenda

• Describe Date data type• Formatting Date data type• Arithmetic on Date data type• Single row functions• Oracle Globalization• Date consideration in flashback

Page 10: Date data type and Globalization in Oracle

Formatting Date data typeFormat Mask Format DescriptionDD Day of the monthMON Month of the yearYY Two-digit yearYYYY Four-digit year including centuryRR Two-digit year (Year 2000-compli-

ant)CC Two-digit centuryHH Hours with AM and PMHH24 Twenty-four-hour timeMI MinuteSS Seconds

Page 11: Date data type and Globalization in Oracle

Formatting Date data typeExample:SQL> select * from test;

C1---------01-NOV-5912-FEB-1712-FEB-17

SQL> select to_char(c1, 'cc yyyy-mm-dd hh24:mi:ss') as mydate from test;

MYDATE----------------------20 1959-11-01 00:00:00

21 2017-02-12 08:58:0221 2017-02-12 08:58:11

SQL> select to_char(c1, 'cc q') as my-date from test;

MYDA----20 421 121 1

Page 12: Date data type and Globalization in Oracle

Formatting Date data typeStandard Syntaxes:

to_char(date, [format], [nls_parameter]),to_date(string, [format], [nls_parameter]),

Page 13: Date data type and Globalization in Oracle

Formatting Date data typeDate Format Masks for Days, Months, and Years:

Format Ele-ment

Description Result

Year Case-sensitive spelling of year Twenty SeventeenMon Three-letter abbreviation of

monthJun

Month Case-sensitive spelling of month

June

Dy Three-letter abbreviation of day

Mon

Day Case-sensitive spelling of day Monday

Page 14: Date data type and Globalization in Oracle

Formatting Date data typeMiscellaneous Date Format Masks:Format Ele-ment

Description Result

- / . , ? # ! Punctuation marks: 'MM.YY' 09.08"any character literal"

Character literals:'"Week" W "of " Month'

Week 2 of September

TH Positional or ordinal text:'DDth "of " Month'

12Th of September

SP Spelled out number:'MmSP Month Yyyysp'

Nine SeptemberTwo Thousand Eight

THSP or SPTH Spelled out positional orordinal number: 'hh24SpTh'

Fourteenth

Page 15: Date data type and Globalization in Oracle

Formatting Date data typeExamples:

SQL> select c1 from test;

C1---------12-FEB-17

SQL> select to_char(c1,'Day "the "ddth "of" Month YYYY') as mytDate from test;

MYTDATE--------------------------------------------------------------------------------Sunday the 12th of February 2017

Page 16: Date data type and Globalization in Oracle

Formatting Date data typeWhat is fm?The names of days and months are automatically padded with spaces. These may be removed using a modifier to the format mask called the fill mode (fm) operator.

Example:SQL> select to_char(c1,'Day "the "ddth "of" Month YYYY') as mytDate from test;

MYTDATE--------------------------------------------------------------------------------Sunday the 12th of February 2017

SQL> select to_char(c1,'fmDay "the "ddth "of" Month YYYY') as mytDate from test;

MYTDATE--------------------------------------------------------------------------------Sunday the 12th of February 2017

Page 17: Date data type and Globalization in Oracle

Formatting Date data typeConverting between calendars:

to_char(date, [format], [nls_parameter]),

There are two nls_parameters:

1. nls_date_language2. nls_calendar

Page 18: Date data type and Globalization in Oracle

Formatting Date data type1. nls_date_language

The NLS_DATE_LANGUAGE parameter specifies the language for the day and the month names produced by the TO_CHAR and TO_DATE functions.

2. nls_calendar

Many different calendar systems are in use throughout the world. NLS_CALENDAR specifies which calendar system Oracle Database uses.

Page 19: Date data type and Globalization in Oracle

Formatting Date data typeExamples:

SQL> select to_char(c1,'fmDay "of" fmMonth') as mydate from test;MYDATE----------------------------------------------------------------------------Tuesday of March

SQL> select to_char(c1,'fmDay "of" fmMonth','nls_date_language=french') as mydate from test;MYDATE------------------------------------------------------------------------Mardi of Mars

SQL> select to_char(c1,'fmDay "of" fmMonth','nls_date_language=persian') as mydate from test;select to_char(c1,'fmDay "of" fmMonth','nls_date_language=persian') as mydate from test *ORA-12702: invalid NLS parameter string used in SQL function

Page 20: Date data type and Globalization in Oracle

Formatting Date data typeHow to use Persian Calendar in Oracle ?

SQL> select to_char(c1,'ddth "of" fmMonth "of" yyyy') as mydate from test;MYDATE----------------------------------------------------21st of March of 2017

SQL> select to_char(c1,'ddth "of" fmMonth "of" yyyy','nls_calendar=persian') as mydate from test;MYDATE------------------------------------------------------------01st of Farvardin of 1396

SQL> select to_char(c1,'yyyy/mm/dd','nls_calendar=persian') as mydate from test;MYDATE----------1396/01/01

Page 21: Date data type and Globalization in Oracle

Formatting Date data typeThe necessity of using to_date function:

For inserting Date in Date data type columns (best practice)

Note: you could use only string formats for inserting Date data type in column based on NLS_DATE_FORMAT parameter, otherwise use to_date function.

Page 22: Date data type and Globalization in Oracle

Formatting Date data typeExamples:

SQL> select * from nls_session_parameters where parameter='NLS_DATE_FORMAT';PARAMETER VALUE-------------------- --------------------NLS_DATE_FORMAT DD-MON-RR

SQL> insert into test values ('1980');insert into test values ('1980') *ORA-01861: literal does not match format string

SQL> alter session set nls_date_format='yyyy';Session altered.

SQL> insert into test values ('1990');1 row created.

Page 23: Date data type and Globalization in Oracle

Formatting Date data typeExamples cont’d:

SQL> select * from nls_session_parameters where parameter='NLS_DATE_FORMAT';PARAMETER VALUE------------------------------ --------------------NLS_DATE_FORMAT yyyy

SQL> insert into test values (to_date('2016-aug-02','yyyy-mon-dd'));1 row created.

SQL> insert into test values (to_date('2016','yyyy'));1 row created.

Page 24: Date data type and Globalization in Oracle

Formatting Date data typeWhat is fx?

fx specifies an exact match for string and the format mask. When the fx modifier is specified, character items that do not exactly match the format mask yield an error.

to_date(string, [format], [nls_parameter])

SQL> insert into test values (to_date('25-DEC-10', 'dd-mon-yyyy'));

1 row created.

SQL> insert into test values (to_date('25-DEC-10', 'fxdd-mon-yyyy'));insert into test values (to_date('25-DEC-10', 'fxdd-mon-yyyy')) *ORA-01862: the numeric value does not match the length of the format item

Page 25: Date data type and Globalization in Oracle

Formatting Date data typeSimplifying the insertion of Persian Date:

SQL> insert into test values (to_date('1363/04/07 10:00','fxyyyy/mm/dd hh24:mi','nls_calendar=persian'));1 row created.

SQL> select to_char(c1,'fmDay "the" ddth "of" Month yyyy') as mtdate from test;MTDATE--------------------------------------------------------------------------------Thursday the 28th of June 1984

SQL> select to_char(c1,'fmDay "the" ddth "of" Month yyyy','nls_calendar=persian') as mtdate from test;MTDATE--------------------------------------------------------------------------------Thursday the 7th of Tir 1363

Page 26: Date data type and Globalization in Oracle

Agenda

• Describe Date data type• Formatting Date data type• Arithmetic on Date data type• Single row functions• Oracle Globalization• Date consideration in flashback

Page 27: Date data type and Globalization in Oracle

Arithmetic on Date data typeWhich arithmetic supported on Date data type:

Date1 – Date2 = Num1

Date1 + Num1 = Date2

Date1 = Date2 + Num1

Page 28: Date data type and Globalization in Oracle

Arithmetic on Date data typeExamples:

SQL> select sysdate - (sysdate + 1) as mydate from dual; MYDATE---------- -1

SQL> select sysdate + 1 as mydate from dual;MYDATE---------14-FEB-17

As you can see, the standard unit in Oracle date arithmetic is one day.

Page 29: Date data type and Globalization in Oracle

Arithmetic on Date data typeFractions of a day:

Precision Day Day Day1 Day 1 1 11 Hour 1/24 1/24 0.04171 Min 1/(24x60) 1/1440 0.0006941 Sec 1/

(24x60x60)1/86400 0.0000115

74

Page 30: Date data type and Globalization in Oracle

Arithmetic on Date data typeExamples:

SQL> select to_char(c1,'yyyy/mm/dd hh24:mi:ss') as mydate from test;MYDATE-------------------2014/02/01 00:00:00

Add 5 minutes:

SQL> select to_char(c1 +(5/1440),'yyyy/mm/dd hh24:mi:ss') as mydate from test;MYDATE-------------------2014/02/01 00:05:00

Page 31: Date data type and Globalization in Oracle

Arithmetic on Date data typeExamples cont’d:The notation in the second column is most commonly used, because it is so much easier to read. Five minutes is 5/(24x60), much easier than 5/1440 or 0.00347.

Subtracting 32 Second:

SQL> select to_char(c1-(32/(24*60*60)),'yyyy/mm/dd hh24:mi:ss') as mydate from test;

MYDATE-------------------2014/01/31 23:59:28

Page 32: Date data type and Globalization in Oracle

Arithmetic on Date data typeOracle date arithmetic with intrinsic functions:Date / Time Math Time Description WHERE (date) > sysdate - 7/24;

Past 7 hours

WHERE (date) > sysdate - 7; Past 7 days WHERE (date) > sysdate - 7/1440;

Past 7 minutes

13/24 13 hours1/24/60/60 One second5/24/60 Five minutes5/24 Five hours

TRUNC(SYSDATE+1/24,'HH') One hour starting with the next hour

Page 33: Date data type and Globalization in Oracle

Agenda

• Describe Date data type• Formatting Date data type• Arithmetic on Date data type• Single row functions• Oracle Globalization• Date consideration in flashback

Page 34: Date data type and Globalization in Oracle

Single row functionsSome important functions:

MONTHS_BETWEENADD_MONTHSLAST_DAYNEXT_DAYSYSDATEROUNDTRUNC

Page 35: Date data type and Globalization in Oracle

Single row functionsMONTHS_BETWEEN:

The MONTHS_BETWEEN(date1, date2) function returns the number of months between two dates.

SQL> alter session set nls_calendar=persian;Session altered.

SQL> select months_between('22-Bahman-1394','22-Ordibehesht-1310') as mydate from dual;

MYDATE----------1016.93548

Page 36: Date data type and Globalization in Oracle

Single row functionsADD_MONTHS:

The ADD_MONTHS(date1, number of months) function returns the date resulting from adding a speci-fied number of months to a date.

SQL> select add_months('22-Bahman-1394',3) as mydate from dual;

MYDATE-------------------22 Ordibehesht 1395

Page 37: Date data type and Globalization in Oracle

Single row functionsLAST_DAY:

The LAST_DAY(date) function returns the last day of the month that the specified date falls into.

SQL> select last_day(to_date('09-Esfand-1395')) as mydate from dual;MYDATE-------------------30 Esfand 1395

SQL> select last_day(to_date('09-Esfand-1394')) as mydate from dual;MYDATE-------------------29 Esfand 1394

Page 38: Date data type and Globalization in Oracle

Single row functionsNEXT_DAY:

The NEXT_DAY(date1, day of the week) function returns the date on which the next specified day of the week falls after the given date.

SQL> select to_char(to_date('09-Esfand-1395'),'fmDay "the" rr/mm/dd') as mydate from dual;MYDATE------------------Monday the 95/12/9

SQL> select to_char(next_day('09-Esfand-1395','Friday'),'fmDay "the" rr/mm/dd') as mydate from dual;MYDATE-------------------Friday the 95/12/13

Page 39: Date data type and Globalization in Oracle

Single row functionsSYSDATE:

The SYSDATE function takes no parameters and returns a date value that represents the current server date and time.

SQL> select to_char(sysdate,'yyyy/mm/dd hh24:mi:ss') as mydate from dual;

MYDATE-------------------1395/11/26 10:38:24

Page 40: Date data type and Globalization in Oracle

Single row functionsROUND:The ROUND(date, date precision format) function round a given date value to the nearest date precision format like day, month, or year.SQL> select to_char(sysdate,'yyyy/mm/dd hh24:mi:ss') as currdate, to_char(round(sysdate,'mm'),'yyyy/mm/dd hh24:mi:ss') as mydate from dual;CURRDATE MYDATE------------------- -------------------2017/02/14 10:52:59 2017/02/01 00:00:00

SQL> select to_char(sysdate,'yyyy/mm/dd hh24:mi:ss') as currdate, to_char(round(sysdate,'hh'),'yyyy/mm/dd hh24:mi:ss') as mydate from dual;CURRDATE MYDATE------------------- -------------------2017/02/14 10:53:28 2017/02/14 11:00:00

Page 41: Date data type and Globalization in Oracle

Single row functionsTRUNC:The TRUNC(date, date precision format) truncate a given date value to the nearest date precision for-mat like day, month, or year.SQL> select to_char(sysdate,'yyyy/mm/dd hh24:mi:ss') as currdate, to_char(trunc(sysdate,'mm'),'yyyy/mm/dd hh24:mi:ss') as mydate from dual;CURRDATE MYDATE------------------- -------------------2017/02/14 10:57:49 2017/02/01 00:00:00

SQL> select to_char(sysdate,'yyyy/mm/dd hh24:mi:ss') as currdate, to_char(trunc(sysdate,'hh'),'yyyy/mm/dd hh24:mi:ss') as mydate from dual;CURRDATE MYDATE------------------- -------------------2017/02/14 10:58:07 2017/02/14 10:00:00

Page 42: Date data type and Globalization in Oracle

Agenda

• Describe Date data type• Formatting Date data type• Arithmetic on Date data type• Single row functions• Oracle Globalization• Date consideration in flashback

Page 43: Date data type and Globalization in Oracle

Oracle GlobalizationNLS Parameters:

NLS (National Language Support) parameters determine the locale-specific behavior on both the client and the server. NLS parameters can be specified in the following ways:

• As initialization parameters on the server

• As environment variables on the client

• With the ALTER SESSION statement

• In SQL functions

Page 44: Date data type and Globalization in Oracle

Oracle GlobalizationAs initialization parameters on the server

You can include parameters in the initialization parameter file to specify a default session NLS environment. These settings have no effect on the client side; they control only the server's behavior. For example:

NLS_TERRITORY = "CZECH REPUBLIC"

Page 45: Date data type and Globalization in Oracle

Oracle GlobalizationAs environment variables on the client

You can use NLS environment variables, which may be platform-dependent, to specify locale-dependent behavior for the client and also to override the default values set for the session in the initialization pa-rameter file. For example:

Linux system:

export NLS_DATE_FORMAT="Day yyyy"

Windows system:

set NLS_DATE_FORMAT=yyyy/mm/dd hh24:mi:ss

Page 46: Date data type and Globalization in Oracle

Oracle GlobalizationWith the ALTER SESSION statement:

You can use NLS parameters that are set in an ALTER SESSION statement to override the default values that are set for the session in the initialization parameter file or set by the client with environment variables.

ALTER SESSION SET NLS_SORT = AZERBAIJANI;

Page 47: Date data type and Globalization in Oracle

Oracle GlobalizationIn SQL functions:

You can use NLS parameters explicitly to hardcode NLS behavior within a SQL function. This practice overrides the default values that are set for the session in the initialization parameter file, client with environment variables and ALTER SESSION statement.

For example:TO_CHAR(hiredate, 'DD/MON/YYYY', ' nls_calendar=persian ')

Page 48: Date data type and Globalization in Oracle

Oracle GlobalizationSetting NLS Parameters and Their Priorities:

Priority Method1 (highest) Explicitly set in SQL functions2 Set by an ALTER SESSION statement3 Set as an environment variable4 Specified in the initialization parame-

ter file5 Default

Page 49: Date data type and Globalization in Oracle

Oracle GlobalizationViews to find current NLS settings:

• nls_database_parameters

• nls_instance_parameters

• nls_session_parameters

Note: NLS_CHARACTERSET, NLS_NCHAR_CHARACTERSET and NLS_RDBMS_VERSION, there are only exist in the nls_database_parameter.

Page 50: Date data type and Globalization in Oracle

Oracle GlobalizationFind all valid CHARACTER SET,TERRITORY,LANGUAGE:

Simply with v$nls_valid_valuesExample:

SQL> select * from v$nls_valid_values where lower(parameter) ='territory';PARAMETER VALUE ISDEP-------------------- ------------------------------ -------------TERRITORY ECUADOR FALSETERRITORY PHILIPPINES FALSETERRITORY ALBANIA FALSE

98 rows selected.

Page 51: Date data type and Globalization in Oracle

Oracle GlobalizationSome important NLS parameters:

• NLS_TERRITORY

• NLS_DATE_FORMAT

• NLS_LANGUAGE (mentioned in section two)

• NLS_CALENDER (mentioned in section two)

Page 52: Date data type and Globalization in Oracle

Oracle GlobalizationNLS_TERRITORY:The territory selection sets defaults for day and week numbering, credit and debit symbols, date for-mats, decimal and group numeric separators, and currency symbols. Some of these can have profound effects on the way your application software will behave.

Parameters American GermanyNLS_TERRITORY american germanyDecimal separa-tor

, .

Currency sym-bol

$ €

First day of week

Sunday Monday

Page 53: Date data type and Globalization in Oracle

Oracle GlobalizationNLS_TERRITORY:

Example:

alter session set NLS_TERRITORY='germany';select to_char(8527,'L999G999') as myChar from dual;€8.527

alter session set NLS_TERRITORY='america';select to_char(8527,'L999G999') as myChar from dual;$8,527

Page 54: Date data type and Globalization in Oracle

Oracle GlobalizationNLS_DATE_FORMAT:The NLS_DATE_FORMAT parameter defines the default date format to use with the TO_CHAR and TO_DATE functions. The NLS_TERRITORY parameter determines the default value of NLS_DATE_FORMAT. The value of NLS_DATE_FORMAT can be any valid date format mask. For example: NLS_DATE_FORMAT = "MM/DD/YYYY“

Country Description ExampleEstonia dd.mm.yyyy 28.02.2003Germany dd-mm-rr 28-02-03Japan rr-mm-dd 03-02-28UK dd-mon-rr 28-Feb-03US dd-mon-rr 28-Feb-03

Page 55: Date data type and Globalization in Oracle

Agenda

• Describe Date data type• Formatting Date data type• Arithmetic on Date data type• Single row functions• Oracle Globalization• Date consideration in flashback

Page 56: Date data type and Globalization in Oracle

Date consideration in flashbackWhat is Flashback Technology ?

Oracle Flashback Technology is a group of Oracle Database features that let you view past states of database objects or to return database objects to a previous state without using point-in-time media re-covery.

Oracle Flashback features use the Automatic Undo Management (AUM) system to obtain metadata and historical data for transactions. They rely on undo data, which are records of the effects of individual transactions. For example, if a user runs an UPDATE statement to change a salary from 1000 to 1100, then Oracle Database stores the value 1000 in the undo data.

Page 57: Date data type and Globalization in Oracle

Date consideration in flashbackUsing Oracle Flashback Query (SELECT AS OF)

To use Oracle Flashback Query, use a SELECT statement with an AS OF clause. Oracle Flashback Query retrieves data as it existed at an earlier time. The query explicitly references a past time through a time stamp or System Change Number (SCN). It returns committed data that was current at that point in time.Uses of Oracle Flashback Query include:

• Recovering lost data or undoing incorrect, committed changes.For example, if you mistakenly delete or update rows, and then commit them, you can immediately undo the mistake.

• Comparing current data with the corresponding data at an earlier time.For example, you can run a daily report that shows the change in data from yesterday. You can compare individual rows of table data or find intersections or unions of sets of rows.

Page 58: Date data type and Globalization in Oracle

Date consideration in flashbackFlashback Example:

SQL> select * from countries where country_name='Iran';no rows selected

SQL> select to_char(sysdate,'rr/mm/dd hh24:mi:ss') as currdate from dual;CURRDATE-----------------17/02/15 15:27:07

SQL> insert into countries values('IR','Iran',4);1 row created.

Page 59: Date data type and Globalization in Oracle

Date consideration in flashbackFlashback Example cont’d:

SQL> select to_char(sysdate,'rr/mm/dd hh24:mi:ss') as currdate from dual;CURRDATE-----------------17/02/15 15:28:29

SQL> select * from countries where country_name='Iran';CO COUNTRY_NAME REGION_ID-- ---------------------------------------- ----------IR Iran 4

Page 60: Date data type and Globalization in Oracle

Date consideration in flashbackFlashback Example cont’d:

SQL> select * from countries as of timestamp to_timestamp('17/02/15 15:27:07','rr/mm/dd hh24:mi:ss')where country_name='Iran';no rows selected

flashback table countries to timestamp to_timestamp('17/02/15 15:27:07','rr/mm/dd hh24:mi:ss');Flashback succeeded.

SQL> select * from countries where country_name='Iran';no rows selected

Page 61: Date data type and Globalization in Oracle

Date consideration in flashbackRelative time:

If you specify a relative time by subtracting from the current time on the database host, the past time is recalculated for each query. For example:

SQL> insert into countries values ('PO','Poland',1);1 row created.

SQL> select * from countries As of timestamp (systimestamp - interval '1' minute) where country_name='Poland';CO COUNTRY_NAME REGION_ID-- ---------------------------------------- ----------PO Poland 1

Page 62: Date data type and Globalization in Oracle

Date consideration in flashbackArguments which could be passed to relevant flashback:select * from countries As of timestamp (systimestamp - interval '1' <argument>);

ArgumentsYear

MonthDayHour

MinuteSecond

Page 63: Date data type and Globalization in Oracle

Date consideration in flashbackRelative or Exact ?

Exact example:select * from countries As of timestamp to_timestamp('17/02/18 10:49:12', 'rr/mm/dd hh24:mi:ss');

Relative example:select * from countries As of timestamp (systimestamp - interval '1' minute);

Method Simplicity AccuracyExact No YesRelative Yes No

Page 65: Date data type and Globalization in Oracle

Question and Answer

https://ir.linkedin.com/in/masoud-haji-hassan-pour

Masoud Haji Hassan [email protected]

Thanksfor your attention