String Functions
10 Functions
String functions are used to manipulate and transform text data. Whether you need to clean up user input, format reports, or extract specific patterns from a dataset, these functions are your primary tools for text processing.
Table of Contents
CONCAT() & CONCAT_WS()
Joins two or more strings into one. CONCAT_WS (With Separator) uses the first argument as a delimiter between the others.
CONCAT(str1, str2, ...) or CONCAT_WS('-', str1, str2)Combining a first_name and last_name into a full_name.
-- Standard concatenationSELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;-- Concatenation with a separator (hyphen)SELECT CONCAT_WS('-', year, month, day) AS formatted_date FROM logs;Unlike the || operator, CONCAT() handles NULL values gracefully by treating them as empty strings, preventing your entire result from becoming NULL.
SUBSTRING() / SUBSTR()
Extracts a specific portion of a string based on a starting position and length.
SUBSTRING(string FROM start_position FOR length)Extracting the area code from a phone number or the domain from an email.
-- Extract characters 1 to 6SELECT SUBSTRING('XQLora-Platform' FROM 1 FOR 6); -- Result: 'XQLora'In PostgreSQL, you can use Regular Expressions inside SUBSTRING. For example, SUBSTRING(email FROM '@(.*)') will extract everything after the '@' symbol.
UPPER() & LOWER()
Converts all characters in a string to uppercase or lowercase.
UPPER(string) / LOWER(string)Standardizing user input for case-insensitive searches (e.g., searching for "john" in a "John" column).
SELECT * FROM users WHERE LOWER(email) = 'user@example.com';Always use LOWER() on both sides of a comparison in a WHERE clause to ensure you don't miss records due to casing differences.
TRIM() / LTRIM() / RTRIM()
Removes leading and trailing spaces (or specified characters) from a string.
TRIM(string)Cleaning data where users accidentally typed spaces before or after their username.
SELECT TRIM(' clean_me '); -- Result: 'clean_me'You can trim specific characters, not just spaces! TRIM(BOTH 'x' FROM 'xXQLorax') will result in 'XQLora'.
LENGTH()
Returns the number of characters in a string.
LENGTH(string)Validating that a password meets a minimum character requirement.
SELECT username FROM users WHERE LENGTH(password) < 8;LENGTH() counts characters, while OCTET_LENGTH() counts bytes. For standard English, they are the same, but for emojis or special characters, OCTET_LENGTH will be higher.
REPLACE()
Replaces all occurrences of a specified substring within a string with a new substring.
REPLACE(string, old_text, new_text)Updating an old company domain in email addresses to a new one.
SELECT REPLACE(email, '@oldcorp.com', '@newcorp.com') FROM employees;REPLACE is case-sensitive. If you need a case-insensitive replacement, you might need to use REGEXP_REPLACE with the 'i' flag.
LEFT() & RIGHT()
Returns a specified number of characters from the left or right side of a string.
LEFT(string, n) / RIGHT(string, n)Getting the last 4 digits of a credit card number for display.
SELECT CONCAT('****', RIGHT(card_number, 4)) FROM payments;If you provide a negative number to LEFT(string, -n), it returns all characters except the last 'n' characters. Very useful for trimming file extensions!
POSITION() / STRPOS()
Returns the location (index) of a specific substring within a string.
POSITION(substring IN string)Finding where the space character is in a full name so you can split it.
SELECT POSITION(' ' IN 'Imam Dwi'); -- Result: 5If the substring is not found, it returns 0. This is a great way to check if a string contains a specific word in a WHERE clause: WHERE POSITION('Urgent' IN subject) > 0.
SPLIT_PART()
Splits a string by a delimiter and returns the part at the specified index.
SPLIT_PART(string, delimiter, part_number)Getting just the first name from a comma-separated "Lastname, Firstname" format.
SELECT SPLIT_PART('Purwanto, Imam', ', ', 2); -- Result: 'Imam'This is much faster and cleaner than combining SUBSTRING and POSITION for extracting data from CSV-formatted columns.
LPAD() & RPAD()
Pads a string to a specific length by adding characters to the left or right.
LPAD(string, total_length, pad_character)Formatting ID numbers to be 5 digits long (e.g., turning "42" into "00042").
SELECT LPAD(user_id::text, 5, '0') FROM users;This is perfect for generating fixed-width files or ensuring sorting works correctly on numeric strings (so '10' doesn't come before '2').