EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL TO_CHAR
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL TO_CHAR

By Aanchal SinghAanchal Singh

PostgreSQL TO_CHAR

Introduction to PostgreSQL TO_CHAR

PostgreSQL provides a set of powerful tools that can help in converting different data types. These can be a date, integer, float to formatted strings. One of the functions which is widely used for this purpose is the TO_CHAR function. The TO_CHAR function in PostgreSQL is used to convert various data types like date or time, integer, floating-point to formatted strings, and also, they can be used to convert formatted strings to specific data types. They are a part of Data type formatting functions. Let us have a look in detail.

Syntax

The syntax for to_char() is as follows:

to_char(expression, format)

Explanation: The to_char() function has two arguments as mentioned above. Both of these arguments are mandatory. The first argument is expression. Bypassing an appropriate value to this argument the data can be converted to any given format. This format can be any of the ones which are explained below. The expression can be a decimal, date, or any numeric value which needs to be converted to character.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

The second argument is the format. This argument signifies the format which is needed for the resultant string.

Return Value: The outcome of the To_Char() function is a string in text format. This string represents the first argument to be formatted according to the specified format. Please note there are other formats also which can be used in addition to the ones mentioned above. Let us have a look at them as well.

Various Formats

The main conversion which TO_CHAR does is for dates. The format for it can be as below:

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,527 ratings)

TO_CHAR(datetime, format)

The format specifiers are as below,

Oracle TO_CHAR Format Specifier
YYYY The year which can be used in 4 digit
YY The year which can be used in 4 digit
MON Abbreviation of Months in a three-letter word like Jan, Feb, etc
MONTH Name of the entire month
MM Numerical format for a month like 1 to 12
DY Abbreviated day (Sun-Sat)
DD Numerical format for a day like a day from 1 to 31
HH24 Time in the 24-hour format which can be 00 to 24
HH or HH12 Time in the 12-hour format like
MI Minutes which will be displayed between 0 to 59
SS Seconds which will be displayed between 0 to 59

In addition to these different patterns which can be used are as below:

Y, YYY or 9,99,999: The year in digits with a comma. This can also be used with numbers. It will return the comma at the mentioned position. Multiple commas can also be given in a given number

Month: The month should be specified in this format that is camel case.

MONTH: The month should be specified in all capital letters

WW: Week number of the year

9 and 0: They are the numeric values that represent the number of digits specified and the leading zeroes in it respectively.

D: It will return the specified position of the decimal character.

RN: It signifies the roman numbers which can range from 1 to 3999

L: This can be used as a currency symbol.

MI: The minus sign which has specified place for numbers which are less than 0.

PL: The plus sign which has specified place for numbers which are more than 0.

How does the PostgreSQL TO_CHAR function work?

Let us have a look at how the TO_CHAR() function works.

TO_CHAR(
TIMESTAMP '2017-08-18 22:30:59',
'HH24:MI:SS'
)

Here the function converts timestamp to a character string with the format of the 24-hour clock.

Code:

TO_CHAR(TIMESTAMP '2017-08-18 22:30:59', 'HH24:MI:SS')
TIMESTAMP '2017-08-18 22:30:59'
TO_CHAR()

Output: 22:30:59

Explanation: Consider the timestamp which takes the date and time as an input. This timestamp is given to the TO_CHAR() function. This function then converts to the format specified. The format here mentioned is HH24:MI: SS. This indicates the 24 hour clock time format. It converts it to the string format having an output as 22:30:59.

Example to Implement TO_CHAR in PostgreSQL

Below are examples to Implement TO_CHAR in PostgreSQL using various methods:

We now know what the to_char() function is and how it works. To understand better let us have a look at some examples.

Example #1

Let us convert a date variable to a string that uses the 24-hour format:

Code:

SELECT
SERVICE_END_DT,
TO_CHAR(
SERVICE_END_DT,
'HH12:MI: SS'
) END_DT
FROM
APP_MAESTRO.SBSCRBRDIM
ORDER BY
SERVICE_END_DT;

Output:

PostgreSQL TO_CHAR1

Explanation: Here the SERVICE_END_DT is being converted to time. The variable which will be for this converted time is END_DT. Above is the output of the query that we have run. It converts the time from 00:00:00 to 12:00:00 as we have specified the 24-hour format.

Example #2

Let us now convert an entire timestamp value into a different format:

Code:

SELECT
SERVICE_END_DT,
TO_CHAR(
SERVICE_END_DT,
'MON-DD-YYYY HH12: MIPM'
) END_DT
FROM
APP_MAESTRO.SBSCRBRDIM
ORDER BY
SERVICE_END_DT;

Output:

PostgreSQL TO_CHAR2

Explanation: The above code converts the service_end_dt to a completely different format. It is taking the Month in three-letter abbreviations, the day in a numbered format, the year in 4 digit number format. The time also is being taken in the 12-hour format with AM or PM is specified. The output that you see is JAN-01-1753 12:00 AM. It is as per the format we have specified.

Example #3

Let us add a currency symbol to the amount present in the table in this example:

Code:

SELECT
customer_key,
amount,
TO_CHAR(
amount,
'L99D99'
) amt
FROM
ODS_ABP.BL1_RC_RATES
ORDER BY
customer_key;

Output:

PostgreSQL TO_CHAR3

Explanation: The above example is selecting a customer key, amount. This amount is then being converted to the amount preceding the $ symbol. If you observe the format in to_char() function you will see that it specifies ‘L99D99’. This adds a ‘$’ in front of the amount specified. The output is hence        -$34.00. Here we have made use of ‘L’ and ‘D’ which were specified in the formats. By using these we have added the currency symbol and the digit position as well.

Conclusion

Like all the functions the to_char() function is a very helpful formatting string function. It helps in formatting the numerical or date values to character or strings in the specified format. This helps in having a uniform format for the entire data set. With the different formats and patterns, it makes it easy to use and convert the data to string and use it or even compare if required.

Recommended Articles

This is a guide to PostgreSQL TO_CHAR. Here we discuss introduction to PostgreSQL TO_CHAR, syntax, how does it work, examples with code and output. You can also go through our other related articles to learn more –

  1. PostgreSQL Date Functions
  2. PostgreSQL Interval
  3. PostgreSQL GRANT
  4. PostgreSQL Trunc()
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more