0% found this document useful (0 votes)
49 views42 pages

4 Oracle Developer Data Types Essentials m4 Slides

This document discusses date and time data types in Oracle databases. It provides information on the DATE, TIMESTAMP, and interval data types and how to work with them. It covers formatting dates and times, extracting components, default and customized formats, literals, and functions for manipulating dates like TRUNC, ADD_MONTHS, and subtracting dates.

Uploaded by

Anitha Rani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views42 pages

4 Oracle Developer Data Types Essentials m4 Slides

This document discusses date and time data types in Oracle databases. It provides information on the DATE, TIMESTAMP, and interval data types and how to work with them. It covers formatting dates and times, extracting components, default and customized formats, literals, and functions for manipulating dates like TRUNC, ADD_MONTHS, and subtracting dates.

Uploaded by

Anitha Rani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Date and Time Data Types

David Berry
http://buildingbettersoftware.blogspot.com/
Storing Date and Time Data

Required in most database applications

Personal data
• Date of birth
• Hire date

Recording an event
• When an order was received
• When a user logged in

How long an action took


• Time to process and ship order
• Duration to complete project task
Module Introduction

Data and time Working with date


data types and time data

Interval data Working with


types interval data types
Date and Time Data Types in Oracle

Data Type Description

DATE Date/time values with precision of one second

TIMESTAMP(n) Date/time values with up to n digits of


fractional second precision

TIMESTAMP(n) WITH Date/time values with up to n digits of


TIME ZONE fractional seconds and an associated time zone
for the value

TIMESTAMP(n) WITH Date/time values with up to n digits of


LOCAL TIME ZONE fractional seconds. Value is converted to local
time zone of the database
Creating Columns With Date/Time Data Types

CREATE TABLE log_messages


(
message_id NUMBER(10) NOT NULL,
msg_time_as_date DATE,
msg_time_as_timestamp TIMESTAMP,
msg_time_as_timestamp_ms TIMESTAMP(3),
msg_time_as_timstamp_with_tz TIMESTAMP(9) WITH TIME ZONE,
msg_time_as_timstamp_with_ltz TIMESTAMP(2)
WITH LOCAL TIME ZONE,
message VARCHAR2(512) NOT NULL
);
Default Formatting of Date/Time Data

SELECT msg_time_as_date, msg_time_as_timestamp, message


FROM log_messages;

MSG_TIME_AS_DATE MSG_TIME_AS_TIMESTAMP MESSAGE


---------------- ------------------------------- --------------------------------------
29-NOV-14 29-NOV-14 10.55.19.905000000 AM This format is not really useful!
29-NOV-14 29-NOV-14 10.55.22.828000000 AM At least not for what I want to do!
29-NOV-14 29-NOV-14 10.55.25.474000000 AM Lets see how to better format the data!
Using TO_CHAR() to Format Data

SELECT
TO_CHAR(msg_time_as_date, 'YYYY-MM-DD HH24:MI:SS') as msg_time_date,
TO_CHAR(msg_time_as_timestamp, 'MONTH DD, YYYY HH24:MI')
AS msg_time_timestamp,
message
FROM log_messages;

MSG_TIME_DATE MSG_TIME_TIMESTAMP MESSAGE


------------------- ------------------------ ---------------------------------
2014-11-29 10:55:19 NOVEMBER 29, 2014 10:55 This format is more useful!
2014-11-29 10:55:22 NOVEMBER 29, 2014 10:55 Now we can come up with something
2014-11-29 10:55:25 NOVEMBER 29, 2014 10:55 that is much more meaningful!
Date Format Codes for TO_CHAR()

Code Description
YYYY Four digit year (e.g. 2014)

YY Two digit year (e.g. 14 for 2014)

MM Numeric identifier of the month, 01–12 (January = 01)

MONTH Full name of the month (e.g. NOVEMBER)

MON Abbreviation for the month (e.g. NOV)

DD Day of the month (01-31)

DAY Name of the day of the week (e.g. MONDAY)


Time Format Codes for TO_CHAR()

Code Description
HH24 Hour of day – 24 hour format (0 – 23)

HH Hour of the day – Twelve hour format (1-12)

AM Meridian (AM or PM)

MI Minutes

SS Seconds

FFn Fractional seconds, n = number of fractional seconds

TZH Time zone hours offset from GMT

TZM Time zone minutes offset from GMT


Other Useful Format Codes for TO_CHAR()

Code Description
Q Quarter (1-4) of the year

WW Week of the year

IW ISO standard week of the year

W Week of the month

D Day of the week (1-7). First day of week varies by cultures

DDD Day of the year (1 – 366)


Using String Literals in Formatted Values

SELECT
appointment_with
TO_CHAR(appointment_time, 'MONTH DD, YYYY “at” HH24:MI') AS appointment_time
FROM appointments;

APPOINTMENT_WITH APPOINTMENT_TIME
------------------- -----------------------------
Bill Clinton NOVEMBER 29, 2014 at 10:00
George W Bush NOVEMBER 29, 2014 at 11:30
Barack Obama NOVEMBER 29, 2014 at 13:00
EXTRACT Function

Syntax
EXTRACT (<component> FROM <date or timestamp>)

Example
SELECT
EXTRACT (year FROM systimestamp) AS year,
EXTRACT (month FROM systimestamp) AS month,
EXTRACT (day FROM systimestamp) AS day,
EXTRACT (hour FROM systimestamp) AS hour,
EXTRACT (minute FROM systimestamp) AS minute,
EXTRACT (second FROM systimestamp) AS second
FROM dual;

YEAR MONTH DAY HOUR MINUTE SECOND


--------- ---------- ---------- ---------- ---------- ----------
2014 11 15 2 0 50.478
Does Anyone Know What Time It Is?

Function Description
SYSDATE Current date/time on the Oracle server (server time zone)

CURRENT_DATE Current date/time in the session (session time zone)

SYSTIMESTAMP Current date/time on the Oracle server as a TIMESTAMP

INSERT INTO log_messages (message_id, message_time, message)


VALUES (1, sysdate, ‘This is a message’);
Specifying Date Literals – ANSI Syntax

INSERT INTO log_messages (message_id, message_time, message)


VALUES
(1, DATE ‘2014-12-01’, ‘This is a message’);

SELECT *
FROM log_messages
WHERE message_time >= DATE ‘2014-11-15’
AND message_time <= DATE ‘2014-11-22’
Specifying Date Literals – TO_DATE() Function

SELECT *
FROM log_messages
WHERE message_time >=
TO_DATE(‘2014-11-15 17:00’, ‘YYYY-MM-DD HH24:MI’)
AND message_time <=
TO_DATE(‘2014-11-15 18:30’, ‘YYYY-MM-DD HH24:MI’)
Timestamp Literals

SELECT *
FROM log_messages
WHERE message_time >= TIMESTAMP ‘2014-11-15 17:00:00.000000’
AND message_time <= TIMESTAMP ‘2014-11-15’ 17:10:30.500000’;
Timestamp Literals with Time Zone

SELECT *
FROM log_messages
WHERE message_time >=
TIMESTAMP ‘2014-11-15 17:00:00.000000 -06:00’;

SELECT *
FROM log_messages
WHERE message_time >=
TIMESTAMP ‘2014-08-01 17:00:00.000000 America/Chicago’;
Time Zone Names

Allowed time zone


V$TIMEZONE_NAMES view
names

Standardized database
http://en.wikipedia.org/wiki/Tz_database
of time zones
Use of Date/Time Literal Strings

Use TO_CHAR(), TO_DATE() and literal strings in your SQL editor

In application, make use of functions on the Oracle driver to convert


Oracle types to/from language types
NLS Settings Related to Date/Time Values

To view settings NLS_DATABASE_PARAMETERS view

To change setting
ALTER SESSION SET parameter_name = new_value
for a session
Important NLS Settings

Setting Description
NLS_DATE_FORMAT Default formatting of date values

NLS_TIMESTAMP_FORMAT Default formatting of timestamp values

NLS_DATE_LANGUAGE Controls language of names of days, months

NLS_TERRITORY Controls what day is considered first day of week


Functions for Use with Dates and Times
Oracle does not provide a date only data type

Sometimes working only with the date component is required


TRUNC() Function

Purpose: Remove the time component from a DATE or TIMESTAMP value

SELECT
TO_CHAR(TRUNC(sysdate), ‘YYYY-MM-DD HH24:MI:SS’) AS MY_DATE
FROM DUAL;

MY_DATE
--------------------
2014-11-29 00:00:00
LAST_DAY() Function

Purpose: Find the last day of the current month the date is in

SELECT
LAST_DAY(TO_DATE(‘2014-07-15 17:00’), ‘YYYY-MM-DD HH24:MI’))
AS MY_DATE
FROM DUAL;

MY_DATE
--------------------
2014-07-31 17:00

Caution: Returned data type is a DATE. Any fractional seconds in a


TIMESTAMP will be lost
NEXT_DAY() Function

Purpose: Find the next named weekday following the given date

SELECT
NEXT_DAY(TO_DATE('2014-07-15 8:00', 'YYYY-MM-DD HH24:MI'),
'FRIDAY') AS MY_DATE
FROM DUAL;

MY_DATE
--------------------
2014-07-18 8:00

Caution: Returned data type is a DATE. Any fractional seconds in a


TIMESTAMP will be lost
Adding Days to a DATE or TIMESTAMP

To add or subtract days, just add or subtract that number from the DATE or
TIMESTAMP value

-- Add one day to the current time (this time tomorrow)


SELECT sysdate + 1 FROM DUAL;

-- Get the date/time for 30 days ago


SELECT *
FROM log_messages
WHERE message_time > sysdate – 30;
Adding Fractional Days

-- Set a date value to one hour in the future


UPDATE study_materials_checkout
SET expiration_date = sysdate + 1/24
WHERE checkout_id = 123;

-- What users have logged in in the last 12 hours


SELECT *
FROM system_logins
WHERE login_date >= sysdate – 0.5;
Adding Months to a DATE or TIMESTAMP

Usage: ADD_MONTHS(<<date>>, <<number of months to add/subtract>>)

SELECT
ADD_MONTHS(DATE '2012-02-01', 12) AS twelve_months_added,
DATE '2012-02-01' + 365 AS added_365_days
FROM DUAL;

TWELVE_MONTHS_ADDED ADDED_365_DAYS
-------------------- -----------------
2013-02-01 2013-01-31

Caution: Returned data type is a DATE. Any fractional seconds in a


TIMESTAMP will be lost
Subtracting Dates

-- Find the difference in dates


SELECT
TO_DATE(‘2014-02-01 15:32’, ‘YYYY-MM-DD HH24:MI’) –
TO_DATE(‘2014-01-17 9:32’, ‘YYYY-MM-DD HH24:MI’) AS diff
FROM DUAL;

DIFF
-----------
15.25

-- Find how long an order took to ship


SELECT ship_date – order_date
FROM orders
WHERE order_id = 123;
Subtracting TIMESTAMP Values

-- Find the difference between two timestamps


SELECT
TIMESTAMP '2014-11-30 22:00:00.00' –
TIMESTAMP '2014-11-30 21:36:14.23' AS DIFF
FROM dual;

DIFF
-----------
+00 00:23:45.770000
Months Between

Usage: MONTHS_BETWEEN(<<date one>>, <<date two>>)

-- Find the difference in months


SELECT
MONTHS_BETWEEN(
DATE ‘2014-02-01’,
DATE ‘2011-09-17’
) as months_different
FROM DUAL;

MONTHS_DIFFERENT
-------------------
28.4838709677419
Calculating the Months Between Two Dates

Purpose: Find the number of months between two dates

SELECT
MONTHS_BETWEEN (DATE '2014-4-08', DATE '2001-08-24') AS DIFF
FROM DUAL;

DIFF
--------------------
151.483870967742

Caution: Returned data type is a DATE. Any fractional seconds in a


TIMESTAMP will be lost
INTERVAL Data Types

INTERVAL YEAR TO INTERVAL DAY TO


MONTH SECOND
INTERVAL YEAR TO MONTH Data Type

Purpose Store periods of time measured in years and months

Can specify up to 9 digits to store the year


Precision
Default precision for years is two
Syntax for INTERVAL YEAR TO MONTH Data Type

INTERVAL YEAR(<<precision>>) TO MONTH

Precision can be from 0-9 digits (default 2)


Creating an INTERVAL YEAR TO MONTH Column

CREATE TABLE employment_experience


(
experience_id NUMBER(10) NOT NULL,
candidate_id NUMBER(10) NOT NULL,
company_name VARCHAR2(25) NOT NULL,
title VARCHAR2(25),
start_date DATE,
employment_length INTERVAL YEAR(2) TO MONTH
);
INTERVAL YEAR TO MONTH Literal Values

Literal value format


INTERVAL ‘<<years>>-<<months>>’ YEAR(<<precision>>) TO MONTH

Example
INSERT INTO employment_experience
(experience_id, candidate_id, company_name, title,
start_date, employment_length)
VALUES
(12345, 100, ‘Pluralsight’, ‘Software Developer’
DATE ‘2010-07-15’,
INTERVAL '4-3' YEAR(2) TO MONTH);
Syntax for INTERVAL YEAR TO MONTH Data Type

INTERVAL DAY(<<precision>>) TO SECOND(<<precision>>)

Days precision can be from Fractional second precision


0-9 digits (default 2) can be from 0-9 digits
(default 6)
Creating an INTERVAL DAY TO SECOND Column

-- Store up to 9999 days, 23 hours, 59 minutes, 59 seconds


CREATE TABLE space_missions
(
mission_id NUMBER(10) NOT NULL,
name VARCHAR2(30) NOT NULL,
mission_start DATE,
time_in_space INTERVAL DAY(4) TO SECOND(0)
);

-- Store time periods less than a day with microsecond precision


CREATE TABLE web_service_requests
(
request_id NUMBER(20) NOT NULL,
request_time DATE NOT NULL,
request_date VARCHAR2(512) NOT NULL,
elapsed_time INTERVAL DAY(0) TO SECOND(6)
);
INTERVAL DAY TO SECOND Literal Values

Literal value format


INTERVAL ‘<days> <hh>:<mi>:<sec>.<ff>’ DAY (<precision>)
TO SECOND(<precision>)

Example
INSERT INTO space_missions
(mission_id, name, mission_start, time_in_space)
VALUES
(12345, ‘Valeri Polyakov’, DATE ‘1994-01-09’,
INTERVAL '437 17:38:00’ DAY(3) TO SECOND(0) );
Module Summary

Date and timestamp


data types Interval data types

How to format data Declaring as columns


Getting the current time Interval calculations
Date functions Using with date values
Date arithmetic

You might also like