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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Storing Binary Data: The BLOB Type →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
Is TIMESTAMP a date and time type in SQL Server?
Which date and time types should you use in SQL Server?
How many fractional seconds can MySQL and SQL Server store?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →