πŸ—“οΈ SQL Utilities & Features
Estimated reading: 3 minutes 34 views

πŸ”€ SQL String Functions – Format, Extract, Clean & Compare Text in SQL

🧲 Introduction – Why SQL String Functions Matter

Strings are everywhereβ€”names, emails, addresses, logs, and messages. In SQL, string functions help you manipulate, extract, format, and analyze textual data efficiently without relying on external processing.

Whether you’re cleaning data, building reports, or parsing inputβ€”SQL string functions are essential for every developer, analyst, or DBA.

🎯 In this guide, you’ll learn:

  • The most-used SQL string functions
  • Platform-specific syntax (MySQL, PostgreSQL, SQL Server)
  • Practical examples and formatting tricks
  • Performance tips and edge case handling

πŸ”‘ 1. Core SQL String Functions (Cross-Platform)

FunctionPurposeExample
LENGTH()Returns length of a stringLENGTH('Hello') β†’ 5
LOWER()Converts to lowercaseLOWER('SQL') β†’ sql
UPPER()Converts to uppercaseUPPER('sql') β†’ SQL
TRIM()Removes leading/trailing whitespaceTRIM(' abc ') β†’ 'abc'
SUBSTRING()Extract part of a stringSUBSTRING('Data', 2, 2) β†’ 'at'
CONCAT()Joins strings togetherCONCAT('Hello', 'World')
REPLACE()Replaces substringREPLACE('abc', 'b', 'x') β†’ 'axc'
POSITION() / CHARINDEX()Finds index of substringPOSITION('a' IN 'data') β†’ 2

πŸ§ͺ 2. Examples of Common Operations

βœ… Concatenate First and Last Name

SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM users;

βœ… Get Domain from Email

SELECT SUBSTRING(email FROM POSITION('@' IN email) + 1) AS domain FROM users;
-- PostgreSQL version

βœ… Replace Dashes with Underscores

SELECT REPLACE(column_name, '-', '_') FROM items;

🧬 3. Case Conversion

-- All platforms
SELECT UPPER('hello'), LOWER('WORLD');

-- Output:
-- 'HELLO', 'world'

πŸ”Ž 4. Trimming & Padding

FunctionDescriptionExample
TRIM()Removes spaces from both sidesTRIM(' abc ') β†’ 'abc'
LTRIM()Removes leading spaces (SQL Server)LTRIM(' abc') β†’ 'abc'
RTRIM()Removes trailing spaces (SQL Server)RTRIM('abc ') β†’ 'abc'
LPAD()Pads left side (MySQL, PostgreSQL)LPAD('42', 5, '0') β†’ '00042'
RPAD()Pads right sideRPAD('42', 5, '*') β†’ '42***'

🎯 5. Finding & Extracting Substrings

βœ… Extract Area Code from Phone Number

SELECT SUBSTRING(phone, 1, 3) AS area_code FROM contacts;

βœ… Find Position of @ in Email

SELECT POSITION('@' IN email) FROM users; -- PostgreSQL, MySQL
SELECT CHARINDEX('@', email) FROM users; -- SQL Server

🧠 6. Platform-Specific Notes

FunctionMySQLPostgreSQLSQL Server
LENGTH()Returns bytesSameUse LEN()
SUBSTRING()StandardStandardSame
CHARINDEX()βŒβŒβœ…
POSITION()βœ…βœ…βŒ
TRIM()βœ…βœ…Use LTRIM/RTRIM

πŸ“˜ 7. Real-World Use Cases

TaskFunction(s) Used
Normalize casingUPPER(), LOWER()
Generate usernamesCONCAT(), SUBSTRING()
Format phone numbersSUBSTRING(), CONCAT()
Clean imported data fieldsTRIM(), REPLACE()
Extract subdomain or domainPOSITION(), SUBSTRING()

⚠️ 8. Common Pitfalls

⚠️ ProblemπŸ’‘ Solution
Using LENGTH() instead of CHAR_LENGTH()For multibyte characters (MySQL)
Case-sensitive searches failingUse LOWER() on both sides of comparison
Platform function mismatchCheck compatibility (CHARINDEX, POSITION)
Unexpected whitespace in outputAlways TRIM() before comparison or display

πŸ“Œ Summary – Recap & Next Steps

SQL String Functions help you manipulate and analyze text data with precision. They are indispensable tools for cleaning, formatting, and reporting on textual content in any relational database.

πŸ” Key Takeaways:

  • Use string functions to extract, format, and transform text
  • Check for platform-specific syntax differences
  • Combine functions for powerful transformations (e.g., TRIM(CONCAT(...)))

βš™οΈ Real-World Relevance:
Used in data cleanup, report formatting, ETL pipelines, web app logic, and even login/registration systems.


❓ FAQ – SQL String Functions

❓ Can I use string functions in WHERE clauses?

βœ… Yes. But using functions on columns may prevent index usage. Prefer transforming literals instead of columns.

❓ What’s the difference between LENGTH and CHAR_LENGTH?

βœ… In MySQL:

  • LENGTH() = byte length
  • CHAR_LENGTH() = character count

❓ Can I use regex in SQL?

βœ… PostgreSQL supports SIMILAR TO, ~, and REGEXP_REPLACE. MySQL supports REGEXP. SQL Server uses LIKE or CLR functions.

❓ Are SQL string functions case-sensitive?

βœ… Depends on collation. In case-sensitive databases, use UPPER() or LOWER() to normalize.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ”€ SQL STRING FUNCTIONS

Or Copy Link

CONTENTS
Scroll to Top