How to Capitalize Each Words' First Letter in PostgreSQL
Database:
Operators:
Table of Contents
Problem
In a PostgreSQL string, you need to make the first letter of each word uppercase and the rest of the letters lowercase.
Example
Our database has a table named student
with data in two columns, id
and full_name
.
id | full_name |
---|---|
1 | ANNE WILLIAMS |
2 | alice brown |
3 | Gary JACKSON |
Let’s change the capitalization of students’ full names by converting this string so that only the first letters of the first and last names are capitalized – just as we’d normally write them.
Solution
We’ll use the INITCAP()
function. Here’s the query you’d write:
SELECT INITCAP (full_name) AS new_full_name FROM student; |
Here’s the result:
new_full_name |
---|
Anne Williams |
Alice Brown |
Gary Jackson |
Discussion
In PostgreSQL, you can use the INITCAP()
function to convert a string to a new string that capitalizes the first letter of every word. All other letters will be lowercase. This function takes one parameter as a string and changes the capitalization for each word as described.
In our example, the full name Anne Williams was originally stored in the column full_name
as ANNE WILLIAMS
; after converting, this full name is Anne Williams
.