postgresql-type conversion function

Introduction

Type conversion functions are used to convert data from one type to another.

CAST function

The CAST (expr AS data_type) function is used to convert expr to the data_type data type; the PostgreSQL type conversion
operator (::)can also achieve the same function.

select cast('100' as INTEGER) as t1, '2023-09-05'::date as t2; 

Insert image description here
If the data cannot be converted to the specified type, an error will be returned:
Insert image description here

to_date function

The to_date(string, format) function is used to convert the string string into the date type according to the format format.
YYYY represents the four-digit year; MM represents the two-digit month; DD represents the two-digit day
format

SELECT to_date('2023/09/05','YYYY/MM/DD');

Insert image description here

to_timestamp

The to_timestamp(string, format) function is used to convert the string string into the timestamp WITH time zone type according to the format format. Among them, HH24 represents the hour in 24-hour format; MI represents minutes; SS represents seconds; MS represents milliseconds.

select to_timestamp('2020-03-15 19:08:00.678', 'yyyy-mm-dd hh24:mi:ss.ms');

Insert image description here

to_char

The to_char(expre, format) function is used to convert timestamp, interval, integer, double precision or numeric
type values ​​into strings in the specified format. Among them, 9 in the format represents the digit; D represents the decimal point. For number formatting options, please refer to the official documentation.

select to_char(current_timestamp, 'HH24:MI:SS'),
 to_char(interval '5h 12m 30s', 'HH12:MI:SS'),
 to_char(-125.8, '999D99');

Insert image description here

to_number

The to_number(string, format) function is used to convert strings to numbers. Among them, L in the format string represents the local currency symbol.

select to_number('¥125.8', 'L999D9');

Insert image description here

implicit type conversion

In addition to explicitly using type conversion functions or operators, PostgreSQL will often automatically perform implicit
conversions of data types.

select 1+'2', 'todo: '||current_timestamp;

Insert image description here

Guess you like

Origin blog.csdn.net/Java_Fly1/article/details/132701375