Careeroza
String Functions
Common String Functions
| Purpose | Standard / PostgreSQL | MySQL | SQL Server | SQLite |
|---|---|---|---|---|
| Upper / lower case | UPPER(s), LOWER(s) | same | same | same |
| Length | LENGTH(s) | CHAR_LENGTH(s) | LEN(s) | LENGTH(s) |
| Part of a string | SUBSTRING(s FROM 1 FOR 3) | SUBSTRING(s,1,3) | SUBSTRING(s,1,3) | SUBSTR(s,1,3) |
| Join strings | s1 || s2 | CONCAT(s1,s2) | s1 + s2 / CONCAT | s1 || s2 |
| Trim spaces | TRIM(s) | same | same (2017+) | same |
| Replace text | REPLACE(s,a,b) | same | same | same |
| Find position | POSITION(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
| CustomerName | Upper | Len | First5 | Underscored |
|---|---|---|---|---|
| Aarav Traders | AARAV TRADERS | 13 | Aarav | Aarav_Traders |
| Blue Harbor Foods | BLUE HARBOR FOODS | 17 | Blue | Blue_Harbor_Foods |
| Cedar & Co | CEDAR & CO | 10 | Cedar | Cedar_&_Co |
| Delta Mart | DELTA MART | 10 | Delta | Delta_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
| ProductName | SpaceAt | FirstWord |
|---|---|---|
| Basmati Rice 5kg | 8 | Basmati |
| Green Tea 100 bags | 6 | Green |
| Olive Oil 1L | 6 | Olive |
| Dark Chocolate | 5 | Dark |
| Espresso Beans 1kg | 9 | Espresso |
| Almonds 500g | 8 | Almonds |