EVIKA.ACADEMY›SQL Tutorial
SQL Tutorial›String Functions

SQL String Functions

Chapter 30 of 40 · Estimated read time: 10 min

Real-world data is messy — extra spaces, inconsistent casing, mixed formats. SQL string functions let you clean, transform, and extract text directly inside a query without touching the raw data. This chapter covers the functions used in almost every data analyst job.

UPPER(s)
Convert to uppercase
LOWER(s)
Convert to lowercase
LENGTH(s)
Count characters
TRIM(s)
Remove leading/trailing spaces
LTRIM(s)
Remove leading spaces only
RTRIM(s)
Remove trailing spaces only
CONCAT(a,b,...)
Join strings together
SUBSTRING(s,p,n)
Extract part of a string
REPLACE(s,old,new)
Swap one substring for another
INSTR(s,sub)
Find position of a substring
LEFT(s,n)
First n characters
RIGHT(s,n)
Last n characters

UPPER and LOWER — Normalise Case

Use these when comparing text that might have inconsistent casing, or to standardise output.

SELECT
  customer_name,
  UPPER(customer_name) AS name_upper,
  LOWER(city)          AS city_lower
FROM customers;
UPPER/LOWER do not change the stored value — only the query output
customer_namename_uppercity_lower
Amit VermaAMIT VERMAnoida
Priya SharmaPRIYA SHARMAdelhi
Rohan MehtaROHAN MEHTAmumbai
-- Case-insensitive search using LOWER
SELECT product_name
FROM products
WHERE LOWER(product_name) LIKE '%cable%';
Matches 'HDMI Cable' even if the user typed 'cable', 'Cable', or 'CABLE'
product_name
HDMI Cable
On MySQL and SQL Server, string comparisons are case-insensitive by default (depending on collation). On PostgreSQL they are case-sensitive. Using LOWER() on both sides is the safest cross-database approach.

LENGTH — Count Characters

LENGTH(string) -- MySQL, PostgreSQL, SQLite LEN(string) -- SQL Server
SELECT
  product_name,
  LENGTH(product_name) AS name_length
FROM products
ORDER BY name_length DESC;
product_namename_length
Ergonomic Chair15
Wireless Mouse14
Ballpoint Pens14
Notebook A511
USB-C Hub9
Desk Lamp9
HDMI Cable10
Use LENGTH in a WHERE clause to find data-quality issues: WHERE LENGTH(phone) != 10 flags phone numbers that are not 10 digits.

TRIM — Remove Whitespace

Data imported from CSV or Excel often has invisible leading/trailing spaces that break JOINs and comparisons. TRIM is the fix.

-- Simulate messy data with spaces
SELECT
  '  Amit Verma  '               AS raw,
  TRIM('  Amit Verma  ')         AS trimmed,
  LTRIM('  Amit Verma  ')        AS left_trimmed,
  RTRIM('  Amit Verma  ')        AS right_trimmed,
  LENGTH('  Amit Verma  ')       AS raw_length,
  LENGTH(TRIM('  Amit Verma  ')) AS clean_length;
Raw has 2 spaces on each side; TRIM removes all surrounding whitespace
rawtrimmedleft_trimmedright_trimmedraw_lengthclean_length
Amit Verma Amit VermaAmit Verma Amit Verma1410

CONCAT — Join Strings

CONCAT(str1, str2, ...) -- MySQL, PostgreSQL, SQL Server str1 || str2 || str3 -- PostgreSQL, SQLite, Oracle (pipe operator) str1 + str2 -- SQL Server alternative
-- Build a full address string
SELECT
  customer_id,
  CONCAT(customer_name, ' — ', city) AS display_name
FROM customers;
customer_iddisplay_name
C01Amit Verma — Noida
C02Priya Sharma — Delhi
C03Rohan Mehta — Mumbai
C04Sneha Gupta — Noida
C05Arjun Singh — Bengaluru
-- Build order reference codes
SELECT
  order_id,
  CONCAT('ORD-', order_id, '-', customer_id) AS order_ref
FROM orders
LIMIT 4;
order_idorder_ref
1001ORD-1001-C01
1002ORD-1002-C02
1003ORD-1003-C01
1004ORD-1004-C03
CONCAT(value, NULL) returns NULL in standard SQL. Use CONCAT_WS(separator, ...) in MySQL/PostgreSQL to safely skip NULLs: CONCAT_WS(', ', first, last) handles NULL gracefully.

SUBSTRING — Extract Part of a String

SUBSTRING(string, start_pos, length) -- start_pos is 1-indexed (first character = 1) -- length is optional — omit to get everything from start_pos to end SUBSTR(string, start, length) -- SQLite / Oracle alias
-- Extract the first word (first name) from customer_name
-- and the category prefix (first 4 chars)
SELECT
  customer_name,
  SUBSTRING(customer_name, 1, INSTR(customer_name, ' ') - 1) AS first_name,
  product_name,
  SUBSTRING(product_name, 1, 4)                              AS short_code
FROM customers
CROSS JOIN (SELECT product_name FROM products LIMIT 1) p
LIMIT 3;
-- Simpler: LEFT / RIGHT shortcuts
SELECT
  customer_id,
  LEFT(customer_id, 1)   AS id_prefix,   -- 'C'
  RIGHT(customer_id, 2)  AS id_number    -- '01', '02' ...
FROM customers;
LEFT and RIGHT are shorthand for SUBSTRING from either end
customer_idid_prefixid_number
C01C01
C02C02
C03C03
C04C04
C05C05

REPLACE — Swap One Substring for Another

REPLACE(string, old_substring, new_substring)
-- Rename a category in output without changing the table
SELECT
  product_name,
  category,
  REPLACE(category, 'Electronics', 'Tech') AS category_clean
FROM products
WHERE category = 'Electronics';
product_namecategorycategory_clean
Wireless MouseElectronicsTech
USB-C HubElectronicsTech
HDMI CableElectronicsTech
-- Remove unwanted characters (e.g. strip commas from a number field)
SELECT REPLACE('1,49,999', ',', '') AS clean_number;
-- Result: '1499999'
REPLACE is case-sensitive in most databases. To do a case-insensitive replace, combine with UPPER/LOWER: REPLACE(LOWER(col), 'old', 'new')

Real-World Example — Data Cleaning in a Single Query

Combine string functions to standardise messy imported data:

-- Imagine raw customer data imported from a form:
-- names have random casing, emails have spaces, phone has dashes
SELECT
  TRIM(UPPER(LEFT(customer_name, 1)))
    || LOWER(SUBSTRING(customer_name, 2)) AS name_clean,
  LOWER(TRIM(email))                      AS email_clean,
  REPLACE(TRIM(phone), '-', '')           AS phone_clean,
  LENGTH(REPLACE(TRIM(phone), '-', ''))   AS phone_digits
FROM raw_customers;
All transformations happen in the SELECT — the raw table is unchanged
name_cleanemail_cleanphone_cleanphone_digits
Amit vermaamit@email.com987654321010
Priya sharmapriya@email.com981234567810

Cross-Database Cheatsheet

TaskMySQLPostgreSQLSQL Server
String lengthLENGTH(s)LENGTH(s)LEN(s)
SubstringSUBSTRING(s,p,n)SUBSTRING(s,p,n)SUBSTRING(s,p,n)
ConcatenateCONCAT(a,b)a || ba + b
Find positionINSTR(s,sub)POSITION(sub IN s)CHARINDEX(sub,s)
Pad leftLPAD(s,n,pad)LPAD(s,n,pad)FORMAT / REPLICATE
Repeat stringREPEAT(s,n)REPEAT(s,n)REPLICATE(s,n)
✏️ Practice Exercises
1. Write a query that shows each product name in UPPERCASE and its character count.
2. Build a "product code" by taking the first 3 letters of the category (UPPER) and joining them with the product_id using a hyphen.
3. Find all products whose name contains a space (use INSTR or LIKE).
Show Answers
-- 1.
SELECT
  product_name,
  UPPER(product_name)  AS name_upper,
  LENGTH(product_name) AS char_count
FROM products;

-- 2.
SELECT
  product_id,
  product_name,
  CONCAT(UPPER(LEFT(category, 3)), '-', product_id) AS product_code
FROM products;
-- e.g. 'ELE-1', 'STA-3', 'FUR-5'

-- 3.
SELECT product_name
FROM products
WHERE product_name LIKE '% %';
-- or: WHERE INSTR(product_name, ' ') > 0