postgresql
  1. postgresql-time

Time - (PostgreSQL Data Types)

PostgreSQL supports a variety of data types, including the time data type. In this tutorial, we'll discuss the syntax, examples, output, explanations, uses, important points, and summary of the time data type in PostgreSQL.

Syntax

The syntax for creating a time column in a table is as follows:

CREATE TABLE table_name (
  column_name  TIME
);

The syntax for inserting time values into a table is:

INSERT INTO table_name (column_name) VALUES ('hh:mm:ss');

The syntax for selecting time values from a table is:

SELECT column_name FROM table_name;

Example

Let's take a look at some examples of using the time data type in PostgreSQL.

Creating a Table

CREATE TABLE employees (
  id SERIAL PRIMARY KEY,
  name VARCHAR(50),
  start_time TIME
);

Inserting Values

INSERT INTO employees (name, start_time) VALUES ('John', '09:00:00');
INSERT INTO employees (name, start_time) VALUES ('Jane', '11:30:00');

Selecting Values

SELECT name, start_time FROM employees;

The output of this query would be:

name | start_time
-----+-----------
John | 09:00:00
Jane | 11:30:00

Explanation

In the above example, we created a table called employees with columns for id, name, and start_time. The start_time column is of the time data type, which stores time values in the format of hh:mm:ss.

We then inserted two rows into the employees table with name and start_time values. We used the SELECT statement to retrieve these values from the table.

Use

The time data type is useful for storing time values, such as the start time of an event, the duration of an activity, or the time of day when a certain process runs.

Important Points

  • The time data type has a range of 00:00:00 to 24:00:00.
  • The time data type can be nullable by adding the NULL keyword in the column definition.
  • The time data type can be converted to and from a string in various formats using functions such as to_char() and to_time().

Summary

In this tutorial, we covered the time data type in PostgreSQL, including its syntax, examples, output, explanation, use, and important points. The time data type is useful for storing time values, and with this knowledge, you can now use the time data type in your PostgreSQL tables and queries.

Published on: