PostgreSQL - Day 6

Keep learning PostgreSQL by Learn PostgreSQL Tutorial - Full Course for Beginners.

Today we’ll learn how to deal with Date and Time.

32. Timestamps and Dates

  • NOW can get the current timestamp.
    • You can cast the timestamp to date by NOW() plus ::DATE.
    • You can cast the timestamp to time by NOW() plus ::TIME.

You don’t have to save all the date/time by timestamp. Instead, you can use several types of Date/Time.

33. Adding and Subtracting with Dates

We can do calculations on DATE/TIME with operators.

  • To get the day ten years ago.
    • But this statement returns timestamp, you have to cast it to date.
      SELECT (NOW() - INTERVAL '10Y')::DATE;
      

34. Extracting Fields

The EXTRACT() function allows us to extract specific values from a date.

  • Extract the year from the date.

  • Extract the day of the week from the date.

    • Sunday is zero.

35. Age Function

The Age function calculates the age.

select id, first_name, date_of_birth, Age(date_of_birth) from person;

comments

comments powered by Disqus