TopicsCheat sheetLessons
Lurndo › Topics › Text functions

Learn SQL: Text functions

Working with text

"Why are there two kinds of novels in my overview?" Sanne frowns. Someone once typed `Novel` with a capital, someone else `novel` without. Time to learn how to tame text.

Functions on text

A function takes a value and gives back a new one, row by row. UPPER puts text in capitals, LOWER in small letters, and LENGTH counts the characters.

The table itself doesn't change: only the result does.

SELECT title, UPPER(title) AS loud, LENGTH(title) AS chars FROM books
Result
titleloudchars
De stille rivierDE STILLE RIVIER16
Nachtwacht in BruggeNACHTWACHT IN BRUGGE20
Het laatste lichtHET LAATSTE LICHT17
Draken van het NoordenDRAKEN VAN HET NOORDEN22
Koken met restjesKOKEN MET RESTJES17
The Glass HarbourTHE GLASS HARBOUR17
Zomer in ZeelandZOMER IN ZEELAND16
De code van MercatorDE CODE VAN MERCATOR20

Cleaning up messy data

To SQLite, novel and Novel are two different values. Grouping by genre therefore gives two little groups of novels (you can see the problem below).

Group by LOWER(genre) and they merge. You can simply use a function in GROUP BY.

SELECT LOWER(genre) AS genre, COUNT(*) AS total FROM books GROUP BY LOWER(genre)
Result
genretotal
comic2
fantasy3
non-fiction3
novel7
thriller5
SELECT genre, COUNT(*) AS total FROM books GROUP BY genre
Without LOWER
genretotal
Novel2
THRILLER1
comic2
fantasy3
non-fiction3
novel5
thriller4

Gluing, cutting and polishing

|| glues text together. SUBSTR(text, start, length) cuts out a piece, counting from 1. REPLACE(text, old, new) swaps text, and TRIM removes spaces at the start and the end.

You can glue numbers on too: SQLite turns them into text.

SELECT author || ': ' || title AS label, SUBSTR(isbn, 1, 3) AS prefix, REPLACE(isbn, '-', '') AS no_dashes FROM books
Result
labelprefixno_dashes
Lies Verbeke: De stille rivier9789789044110013
Tom Janssens: Nachtwacht in Brugge9789789044110020
Ann De Wilde: Het laatste licht9789789044110037
Kris Maes: Draken van het Noorden9789789044110044
Sara Peeters: Koken met restjes9789789044110051
Emily Hart: The Glass Harbour9789781840010068
Lies Verbeke: Zomer in Zeeland9789789044110075
Tom Janssens: De code van Mercator9789789044110082

Try it yourself

Make labels for the shelves. Show each book's title with its year after it in brackets, for example Het eiland (2011).

Ready for more?

The full lesson has 6 exercises, from easy to challenging, with hints, points and a streak you can build.

Start the lesson
← PreviousJoining a table to itselfNext →Calculating with dates
SQL topicsCheat sheetExcelLeaderboardAccountPrivacyNederlands