Capitalize only the first letter of a value in SQL
City names, product codes and statuses stored lowercase need just one letter fixed.
The task
When 'london' should read 'London', you only need the first character capitalized, leaving the rest of the word alone.
The snippet
Written for SQL Server. Versions for PostgreSQL and MySQL are under Variations.
SELECT UPPER(LEFT(city, 1)) + LOWER(SUBSTRING(city, 2, LEN(city))) AS city_display
FROM addresses;
작동 방식
LEFT takes the first character, UPPER capitalizes it, and LOWER(SUBSTRING(...)) lowercases everything after position one. Concatenating the pieces gives 'london' -> 'London' and 'LONDON' -> 'London'. Drop the LOWER if the rest must stay as stored: with it, 'new York' becomes 'New york'.
Variations
PostgreSQL
PostgreSQLSELECT UPPER(LEFT(city, 1)) || LOWER(SUBSTRING(city FROM 2)) AS city_display
FROM addresses;
MySQL
MySQLSELECT CONCAT(UPPER(LEFT(city, 1)), LOWER(SUBSTRING(city, 2))) AS city_display
FROM addresses;
Questions that come up
What about a NULL or empty string?
NULL in gives NULL out, because every function and the concatenation propagate NULL; wrap it in COALESCE if you need a default. An empty string comes back as an empty string on SQL Server, PostgreSQL and MySQL. Oracle treats '' as NULL anyway.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.