How to Convert the Case of a String in PostgreSQL

In PostgreSQL, there are several functions available to modify the case of a string. Whether you need to convert all letters to uppercase, lowercase, or capitalized form, PostgreSQL provides easy-to-use built-in functions for these tasks. In this tutorial, we'll explore the following functions:

  • UPPER(): Converts all characters in a string to uppercase.
  • LOWER(): Converts all characters in a string to lowercase.
  • INITCAP(): Capitalizes the first letter of each word in the string.

1. UPPER() Function

The UPPER() function converts all characters in a string to uppercase. Here's an example:

SELECT UPPER('hello world');

This query will return 'HELLO WORLD'.

2. LOWER() Function

The LOWER() function converts all characters in a string to lowercase. Here's an example:

SELECT LOWER('HELLO WORLD');

This query will return 'hello world'.

3. INITCAP() Function

The INITCAP() function capitalizes the first letter of each word in a string, while converting the rest of the letters to lowercase. Here's an example:

SELECT INITCAP('hello world');

This query will return 'Hello World'.

Use Case: Cleaning Data

These functions can be particularly useful when cleaning and formatting data. For example, if you have a list of names in various cases, you can use INITCAP() to ensure that all names are properly capitalized, while UPPER() or LOWER() can be used for standardizing formats like email addresses.

Conclusion

PostgreSQL provides powerful functions like UPPER(), LOWER(), and INITCAP() to make string case conversion simple. These functions can be incredibly useful when managing and normalizing text data. For more advanced string manipulation, you can combine these functions with others such as TRIM() and CONCAT() to create more complex transformations.