String Functions

Common String Functions

PurposeStandard / PostgreSQLMySQLSQL ServerSQLite
Upper / lower caseUPPER(s), LOWER(s)samesamesame
LengthLENGTH(s)CHAR_LENGTH(s)LEN(s)LENGTH(s)
Part of a stringSUBSTRING(s FROM 1 FOR 3)SUBSTRING(s,1,3)SUBSTRING(s,1,3)SUBSTR(s,1,3)
Join stringss1 || s2CONCAT(s1,s2)s1 + s2 / CONCATs1 || s2
Trim spacesTRIM(s)samesame (2017+)same
Replace textREPLACE(s,a,b)samesamesame
Find positionPOSITION(a IN s)LOCATE(a,s)CHARINDEX(a,s)INSTR(s,a)

Examples

Example

Apply several string functions to customer names:

SELECT CustomerName,
       UPPER(CustomerName) AS Upper,
       LENGTH(CustomerName) AS Len,
       SUBSTR(CustomerName, 1, 5) AS First5,
       REPLACE(CustomerName, ' ', '_') AS Underscored
FROM Customers
LIMIT 4;

Result: 4 rows

CustomerNameUpperLenFirst5Underscored
Aarav TradersAARAV TRADERS13AaravAarav_Traders
Blue Harbor FoodsBLUE HARBOR FOODS17Blue Blue_Harbor_Foods
Cedar & CoCEDAR & CO10CedarCedar_&_Co
Delta MartDELTA MART10DeltaDelta_Mart

Building Strings

Example

Build a short label for each employee:

SELECT UPPER(SUBSTR(LastName, 1, 1)) || '. ' || FirstName || ' (' || Department || ')' AS Label
FROM Employees;

Result: 6 rows

Label
V. Rahul (Sales)
K. Sara (Sales)
L. David (Sales)
I. Ananya (Support)
T. James (Support)
A. Fatima (Finance)

Searching Inside Strings

Example

Split the product name at the first space:

SELECT ProductName,
       INSTR(ProductName, ' ') AS SpaceAt,
       SUBSTR(ProductName, 1, INSTR(ProductName, ' ') - 1) AS FirstWord
FROM Products;

Result: 6 rows

ProductNameSpaceAtFirstWord
Basmati Rice 5kg8Basmati
Green Tea 100 bags6Green
Olive Oil 1L6Olive
Dark Chocolate5Dark
Espresso Beans 1kg9Espresso
Almonds 500g8Almonds