NO. 06 · 7 exercises

6. String Functions

Cut, clean and glue text inside a query.

The lesson

String Functions

Databases are full of text — names, titles, emails — and humans are full of ways to enter it wrong. Mixed capitalization, stray spaces, an & that breaks a URL. So far you could only compare text (LIKE) and sort it. This chapter gives you the tools to cut, clean and glue it: join names together, trim padding, find a needle in a haystack, change cases.

Every function here takes a string and hands you back a new one — remember, the table itself never changes, you only change the answer.

Gluing strings: ||

Our customers table splits every name into first_name and last_name. The newsletter wants one field. Glue them:

SELECT first_name || ' ' || last_name AS full_name
FROM customers;

The || operator joins (concatenates) two strings. Note the ' ' in the middle — SQL doesn't add spaces for you. Daniel + ' ' + Brooks becomes Daniel Brooks, and full_name is just an alias for the new computed column, exactly like the expressions you met in chapter 1.

You can chain as many pieces as you like: 'Mr. ' || first_name || ' ' || last_name works fine.

Measuring: LENGTH

How long is a track title? LENGTH counts characters:

SELECT title, LENGTH(title) AS chars
FROM tracks;

This is where the data starts talking back. La Marea is 8 characters, The Frozen Choir 16 — and ' solstice ' measures 12, because those two sneaky spaces at each end are characters too. That will matter in a moment.

Screaming and whispering: UPPER and LOWER

Track 6 was typed all lowercase into the catalog: midnight train. UPPER and LOWER rescale any string:

SELECT UPPER(title) AS caps, LOWER(title) AS lower
FROM tracks
WHERE id = 6;

You get MIDNIGHT TRAIN and midnight train. Where these really shine is case-insensitive searching. If a customer types MIDNIGHT TRAIN, the plain comparison title = 'MIDNIGHT TRAIN' fails against the stored midnight train. Compare the normalized versions instead:

SELECT title FROM tracks
WHERE LOWER(title) = 'midnight train';

Now the match works no matter how the customer capitalized it. (LIKE is case-insensitive for plain ASCII letters in SQLite, but LOWER(...) = ... works for every language, accented characters included — a safer habit.)

Trimming: TRIM

Remember ' solstice ', the title with padding on both sides? Nobody wants two leading spaces in a sleeve booklet. TRIM shaves them off:

SELECT TRIM(title) AS clean_title
FROM tracks
WHERE id = 17;

TRIM removes spaces (and tabs) from both ends. If the mess is only on one side, SQLite also has LTRIM (left only) and RTRIM (right only). You can even tell it which characters to trim: TRIM(title, ' .') would also strip periods.

A classic double act: LENGTH(TRIM(title)) — clean it, then measure it, to prove the padding is gone.

Slicing: SUBSTR

SUBSTR(string, start, length) cuts a piece out of a string. Count starts at 1, not 0:

SELECT SUBSTR(first_name, 1, 1) AS initial FROM customers;

That's the first letter of every customer's first name — D, L, P... Take the first character of both names, add dots, and you've got receipt-ready initials:

SELECT SUBSTR(first_name, 1, 1) || '.' || SUBSTR(last_name, 1, 1) || '.' AS initials
FROM customers;

SUBSTR is flexible: a negative start counts from the end (SUBSTR('Golden Hour', -4) is Hour), and if you leave out the length you get the rest of the string — which will be useful in the boss exercise.

Swap and fix: REPLACE

REPLACE(string, from, to) finds every occurrence of one text and substitutes another:

SELECT REPLACE(title, '&', 'and') AS fixed_title
FROM tracks
WHERE title = 'Static & Honey';

Static & Honey becomes Static and Honey. REPLACE is the great fixer-upper for dirty data: wrong spellings, stray characters, broken separators — find it, replace it, move on. It replaces all occurrences, not just the first.

Finding the needle: INSTR

Sometimes you don't need the text cut — you need to know where something is. INSTR(haystack, needle) returns the position of the first occurrence, or 0 if it's not there:

SELECT email, INSTR(email, '@') AS at_position
FROM customers;

dbrooks@postmail.com puts its @ at position 8. Combine INSTR with SUBSTR and you can split any string at any marker — which is exactly the trick the next section needs.

The email toolkit

Marketing wants each customer email split into its local part (before the @) and its domain (after it). One query, built from two pieces you already know:

SELECT email,
       SUBSTR(email, 1, INSTR(email, '@') - 1) AS local_part,
       SUBSTR(email, INSTR(email, '@') + 1) AS domain
FROM customers;

Read it like a recipe. INSTR(email, '@') finds where the @ lives. The local part is everything from position 1 up to one before it; the domain is everything from one after it to the end (no length given — take the rest). For cami.rocha@correo.br you get cami.rocha and correo.br, for every one of the 15 customers.

What you just learned

  • || glues strings together — you supply every character, spaces included.
  • LENGTH counts characters; UPPER/LOWER change case, and LOWER(...) = ... makes comparisons case-insensitive.
  • TRIM (plus LTRIM/RTRIM) strips padding from the ends.
  • SUBSTR cuts a piece out of a string (counting from 1); REPLACE swaps text; INSTR finds a position, and returns 0 when the needle is missing.
  • Functions compose: INSTR + SUBSTR splits emails; LENGTH + TRIM proves cleanliness.

Dialect note. SQLite joins strings with || — the same operator as PostgreSQL and SQL Server. MySQL uses a function instead: CONCAT(a, b), where || means something else entirely (logical OR). Similarly, SQLite's SUBSTR is called SUBSTRING in most other databases. The rest — UPPER, LOWER, LENGTH, TRIM, REPLACE, INSTR — exist everywhere under these names. And SQLite counts characters, not bytes, so LENGTH('Cafeína') is 7, not 8.

Time to get your hands on the data. The exercises below assume you've read this far.