π€ 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)
Function | Purpose | Example |
---|---|---|
LENGTH() | Returns length of a string | LENGTH('Hello') β 5 |
LOWER() | Converts to lowercase | LOWER('SQL') β sql |
UPPER() | Converts to uppercase | UPPER('sql') β SQL |
TRIM() | Removes leading/trailing whitespace | TRIM(' abc ') β 'abc' |
SUBSTRING() | Extract part of a string | SUBSTRING('Data', 2, 2) β 'at' |
CONCAT() | Joins strings together | CONCAT('Hello', 'World') |
REPLACE() | Replaces substring | REPLACE('abc', 'b', 'x') β 'axc' |
POSITION() / CHARINDEX() | Finds index of substring | POSITION('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
Function | Description | Example |
---|---|---|
TRIM() | Removes spaces from both sides | TRIM(' 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 side | RPAD('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
Function | MySQL | PostgreSQL | SQL Server |
---|---|---|---|
LENGTH() | Returns bytes | Same | Use LEN() |
SUBSTRING() | Standard | Standard | Same |
CHARINDEX() | β | β | β |
POSITION() | β | β | β |
TRIM() | β | β | Use LTRIM/RTRIM |
π 7. Real-World Use Cases
Task | Function(s) Used |
---|---|
Normalize casing | UPPER() , LOWER() |
Generate usernames | CONCAT() , SUBSTRING() |
Format phone numbers | SUBSTRING() , CONCAT() |
Clean imported data fields | TRIM() , REPLACE() |
Extract subdomain or domain | POSITION() , SUBSTRING() |
β οΈ 8. Common Pitfalls
β οΈ Problem | π‘ Solution |
---|---|
Using LENGTH() instead of CHAR_LENGTH() | For multibyte characters (MySQL) |
Case-sensitive searches failing | Use LOWER() on both sides of comparison |
Platform function mismatch | Check compatibility (CHARINDEX , POSITION ) |
Unexpected whitespace in output | Always 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 lengthCHAR_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 :