Date and Time Data Types: DATE, TIME, and TIMESTAMP, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 4.4 Free with a free account

Date and Time Data Types: DATE, TIME, and TIMESTAMP

Database Programming · Chapter 4: SQL Data Types in DepthSection 4.4 · lesson 23 of 769 min · free with a free account

← Working with BOOLEAN Values in SQLNext lesson: Storing Binary Data: The BLOB Type →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Choosing date and time types and handling ranges, precision, and time zones.

  • Compare the ranges and uses of DATE, TIME, DATETIME, and TIMESTAMP in MySQL
  • Identify SQL Server's DATE, TIME, DATETIME2, and DATETIMEOFFSET types and their older alternatives
  • Explain how UTC, offsets, and session time zones affect stored moments
  • Apply deliberate fractional-second precision and current-time defaults

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,145 words). Read along, or search it.

Opening Question

February 30 Survives as Text in SQLite

Sofia Alvarez, a sales associate at Lantern Books, enters an impossible order date: February thirtieth. This disposable SQLite column is declared date. Does that type name alone guarantee a real calendar day? Run the file, and inspect the stored value and its storage class. The impossible date survives as text. SQLite has no dedicated date storage type, so this declaration does not provide calendar validation. In database systems with temporal types, those types support calendar operations and validation. MySQL's exact rejection behavior still depends on its configured modes. We need two decisions: what time information the value represents, and how our chosen engine stores and validates it.

Date Formats

Year-First ISO Dates and Fractional Seconds

Write dates with the year first, then month and day. Slash dates can mean different days to different readers or server settings. The I S O convention gives this demonstration an unambiguous date, plus a twenty-four-hour clock time and fractional seconds. Run the query, which extracts day and clock components from an illustrative time on our first order date. The day is September first, twenty twenty-six. The clock includes two hundred fifty milliseconds after nine thirty in the morning. Those fractional digits describe precision, not a time zone. A local clock value alone does not identify a unique moment around the world. SQLite can represent times as standardized text, Julian day numbers, or Unix seconds. We use consistent text here, with date functions when conversion is needed.

MySQL Types

MySQL DATE, TIME, DATETIME, TIMESTAMP, and YEAR

MySQL offers date for a calendar day, and time for a clock reading or a duration. Those are different uses of the same type. Its time range extends beyond eight hundred hours in either direction, so it can represent a forty-hour interval. SQL Server's time cannot do that. Datetime combines a day and clock time, without inherent time-zone information. Date and datetime cover years one thousand through nine thousand nine hundred ninety-nine. Timestamp also combines day and time, but uses a much narrower range: early nineteen seventy through January twenty thirty-eight in MySQL eight. Year stores a year alone, from nineteen hundred one through twenty-one fifty-five, plus its special zero value. Base storage differs by type, as the comments show. Time, datetime, and timestamp support up to six fractional digits, adding up to three bytes. For milliseconds, request precision three explicitly. Do not assume the default precision preserves fractional seconds.

SQL Server Types

DATETIME2, DATETIMEOFFSET, and Older SQL Server Types

SQL Server's date and datetime two reach from year one through nine thousand nine hundred ninety-nine. Its time type stores only a clock reading. Datetime two is the usual modern choice for a day and time without an offset. Datetime offset also preserves an offset from coordinated universal time. These modern time-bearing types support up to seven fractional digits, with seven as the default. Storage varies with the requested precision. The older datetime type begins in seventeen fifty-three, and its time resolution is roughly three point three three milliseconds. Small datetime covers nineteen hundred through twenty seventy-nine, at minute precision. Keep these older types for compatibility when needed, rather than choosing them automatically. For a year alone, SQL Server can use smallint. It has no MySQL-style year type, and a time duration usually needs a separate numeric representation.

Common Mistake

TIMESTAMP Means ROWVERSION in SQL Server

The word timestamp is a migration trap. In SQL Server, it is an old, deprecated synonym for rowversion, not a date-and-time type. Rowversion is an automatically generated binary version token. Its counter changes on qualifying inserts and updates; it does not tell you the wall-clock time. If Sofia needs a modification time, choose an actual temporal column, and explicitly arrange for the application or database logic to maintain it. A creation-time default does not automatically refresh whenever a row changes. A version token and a modification timestamp answer different questions. Meanwhile, a long contract ending after twenty thirty-eight needs a broader MySQL type, such as date or datetime. The name timestamp is not enough guidance.

Quick Check

Keeping Only the Time Component

Two new appointments are stored as full date-and-time text. The report keeps only the time component of each value. How many distinct clock readings survive? Pause and predict.

Answer

Dropping the Day Loses Information

One clock reading survives, the first choice. Both appointments reduce to nine in the morning. Run the query, and the count confirms one distinct clock value. Two would count appointments while retaining their different days. Dropping the day loses information. Choose a combined date-and-time type when the schedule must distinguish these appointments.

Time Zones

UTC, Offsets, and Session Time Zones

Coordinated universal time, or U T C, provides a common reference for moments. An offset says how many hours and minutes a local clock differs. MySQL converts timestamp values from the session zone to U T C for storage, then into the reading session's zone. In this illustration, noon entered in a U T C session appears as five thirty in the afternoon, after switching to plus five thirty. A datetime column keeps noon, without that session-zone conversion. Neither type preserves the original named time zone as part of the value. SQL Server's datetime offset preserves a numeric offset alongside the date and time. Supported offsets span minus fourteen through plus fourteen hours. An offset does not identify a named zone or encode its daylight-saving rules. Store the required zone identity separately when scheduling depends on those rules.

Defaults

Filling Creation Times With CURRENT_TIMESTAMP

A default supplies a value when an insert omits the column. Current timestamp is evaluated for the insertion, rather than being fixed when the schema is written. This SQLite example stores the current moment as U T C text. We test whether it was filled, without displaying a changing wall-clock value. Run the insert that names only the event identifier. The database supplies the omitted creation value. The result confirms a filled text value. An explicit null would not request this default; it would violate our not-null constraint. For MySQL datetime or timestamp, declare default current timestamp. Its optional on update clause is separate, and must be requested when wanted. SQL Server's sys date time function supplies datetime two; sys date time offset supplies an offset value. Its current timestamp returns the older datetime type.

Quick Check

Comparing Moments Across Offsets

Two new event records use different clock readings and offsets. One says ten in the morning, minus four hours; the other says fourteen hundred, U T C. After SQLite normalizes both with its datetime function, what does the equality test return? Pause and predict. One, the middle choice, means both normalized values represent the same instant. Run the comparison: adding four hours to the first clock reaches fourteen hundred U T C. The normalized representations agree. Zero would mean different normalized moments. Null would mean an unknown result, which these valid supplied timestamps do not produce.

Key Takeaways

Match the Temporal Type to the Fact

Match the type to the fact: a day, a clock reading, a local appointment, or a globally identified moment. Use unambiguous formats, deliberate fractional precision, and explicit defaults. Check the engine's range and validation rules before accepting input. Sofia's order date needs validation, while globally compared events need a clear zone policy. Similar-looking type names cannot settle either decision.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Date and Time Data Types: DATE, TIME, and TIMESTAMP

What is the difference between DATETIME and TIMESTAMP in MySQL?
Both store a date and a time, but MySQL TIMESTAMP converts values from the session time zone to UTC for storage and back to the reading session's zone, while DATETIME keeps the value as written. TIMESTAMP also has a much narrower range, from 1970 to January 2038, whereas DATETIME covers years 1000 through 9999. Neither type keeps the original named time zone, so store that separately when scheduling depends on it.
Is TIMESTAMP a date and time type in SQL Server?
No, in SQL Server TIMESTAMP is a deprecated synonym for ROWVERSION, an automatically generated binary version token that changes when a row is inserted or updated. It does not record a wall-clock time. For a date and time without an offset, use DATETIME2, and for a value that keeps its offset from UTC, use DATETIMEOFFSET. A MySQL schema that declares TIMESTAMP therefore needs translation rather than copying.
Which date and time types should you use in SQL Server?
For new SQL Server tables, use DATE for a calendar day, TIME for a clock reading, DATETIME2 for a date and time without an offset, and DATETIMEOFFSET when the offset from UTC must be kept. DATE and DATETIME2 cover years 1 through 9999. The older DATETIME starts in 1753 with roughly 3.33 millisecond resolution, and SMALLDATETIME covers 1900 through 2079 at minute precision, so keep those mainly for compatibility.
How many fractional seconds can MySQL and SQL Server store?
MySQL TIME, DATETIME, and TIMESTAMP can store up to six fractional-second digits, or microseconds, but the default precision is zero, so declare DATETIME(3) to keep milliseconds. In SQL Server, TIME, DATETIME2, and DATETIMEOFFSET store up to seven fractional digits, with seven as the default. Storage grows with the requested precision in both systems, so request the detail the data actually needs.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →