// SQL snippet

Capitalize only the first letter of a value in SQL

City names, product codes and statuses stored lowercase need just one letter fixed.

Main statement
SQL Server
Deckt außerdem ab
PostgreSQL MySQL

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.

SQL Server
SELECT UPPER(LEFT(city, 1)) + LOWER(SUBSTRING(city, 2, LEN(city))) AS city_display
FROM addresses;

So funktioniert es

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

PostgreSQL
SELECT UPPER(LEFT(city, 1)) || LOWER(SUBSTRING(city FROM 2)) AS city_display
FROM addresses;

MySQL

MySQL
SELECT 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

// snippets are better with a schema brain

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.