…
…
SQL and Database Fundamentals · Lesson 26 / 41 · Type, text, and date conversions
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The IT office will send a bulk email to all students and wants the list from you. But 9 of the 120 students have no address at all, and some addresses were typed in capital letters or with spaces at the start or end. In this lesson you will find the dirty addresses, count them, clean them, extract parts from the clean address, and build suggested addresses for the students who have none.
So far, your queries took the value in the table as it was: you selected a column, filtered it, counted it, grouped it. With real data this is not always enough. People type addresses in capital letters, add a space at the end when they copy and paste, and enter the same information in different forms. The database stores these values faithfully, but your query does not treat them as "the same". This lesson explains the text functions that fix and split text columns inside a query, in three families: fix text so you can compare it, split text to get information, and reshape text into the form you need.
In this lesson you will:
LENGTH, then count the dirty addresses and sort them by type.LOWER and TRIM, and extract parts from the student number and from the address.REPLACE and TRANSLATE.In the list from the IT office, three addresses look like this:
| first_name | last_name | email (on screen) |
|---|---|---|
| Felix | Abara | felix.abara@students.northbridge.example |
| Isabella | Popescu | ISABELLA.POPESCU@STUDENTS.NORTHBRIDGE.EXAMPLE |
| Elena | Singh | elena.singh@students.northbridge.example |
The problem with Isabella's address is easy to see: every letter is a capital. Felix's and Elena's addresses look perfectly clean. But both have a space at the end, and there is no way to see that space on screen. A space is a character; the table stores it like a letter, but the screen draws it as empty room. This makes the space the sneakiest kind of dirt in data. A mail server may return an error when it sends to such an address, and your query will not find the student when you search by the address.
Start with the visible problem. You want to look up Isabella by her address:
SELECT first_name, last_name FROM student WHERE email = 'isabella.popescu@students.northbridge.example';
Result: 0 rows.
Equality (=) compares two strings character by character, and I and i are different characters. What you call "the same address" on screen is a completely different string for the database. Felix's address has the right letters, but it does not match either. To prove it, you have to measure what you cannot see. LENGTH(text) gives the number of characters in a string and counts spaces too:
SELECT first_name, last_name, LENGTH(email) AS length, LENGTH(TRIM(email)) AS clean_length FROM student WHERE student_no = '202604001';
| first_name | last_name | length | clean_length |
|---|---|---|---|
| Felix | Abara | 41 | 40 |
(1 row)
If you count felix.abara@students.northbridge.example, you get 40 characters; the value in the table has 41. The extra character is the space at the end. TRIM removes that space, so the second column shows 40. Because student_no is text (lesson 25), we wrote it in quotes. When the two lengths differ, you know for sure that the address has a space at the start or the end.
What does this query return?
SELECT LENGTH('Ada ');
After you find the dirt, you need to produce the clean form. Two members of the family are enough for this:
LOWER(text) turns all letters into lowercase, and UPPER(text) turns them into uppercase.TRIM(text) removes the spaces at the start and the end. To remove only the leading spaces there is LTRIM, and for only the trailing spaces there is RTRIM.An address can have both capital letters and spaces, so you apply the two together: LOWER(TRIM(email)). Functions can be nested, and the innermost one runs first; its result becomes the input of the outer one. For ' Tomas.Lindqvist@students.northbridge.example' the steps are:
| Step | Expression | Result |
|---|---|---|
| 1 (inner) | TRIM(' Tomas.Lindqvist@students.northbridge.example') | Tomas.Lindqvist@students.northbridge.example |
| 2 (outer) | LOWER('Tomas.Lindqvist@students.northbridge.example') | tomas.lindqvist@students.northbridge.example |
Now find all dirty addresses in a single query. The logic is simple: an address that is not equal to its clean form is dirty. To make the spaces visible we use the || operator from lesson 3: when you wrap the address in double quotes, a trailing space shows up before the closing quote.
Example 1 (case): Dirty addresses and their clean forms
SELECT student_no, '"' || email || '"' AS raw, LOWER(TRIM(email)) AS clean FROM student WHERE email <> LOWER(TRIM(email)) ORDER BY student_no;
| student_no | raw | clean |
|---|---|---|
| 202304001 | "ISABELLA.POPESCU@STUDENTS.NORTHBRIDGE.EXAMPLE" | isabella.popescu@students.northbridge.example |
| 202307003 | "Ivan.costa@students.northbridge.example" | ivan.costa@students.northbridge.example |
| 202404005 | "MAYA.HASSAN@STUDENTS.NORTHBRIDGE.EXAMPLE" | maya.hassan@students.northbridge.example |
| 202404006 | "MINA.MBEKI@STUDENTS.NORTHBRIDGE.EXAMPLE" | mina.mbeki@students.northbridge.example |
| 202406001 | "liam.lindqvist@students.northbridge.example " | liam.lindqvist@students.northbridge.example |
(first 5 of 17 rows)
17 addresses are dirty. The rest of the list includes addresses with a space at the end, such as "felix.abara@students.northbridge.example " and "elena.singh@students.northbridge.example ", one address with two spaces at the start, " tomas.lindqvist@students.northbridge.example", and addresses where only the first letter is a capital, such as "Salma.costa@students.northbridge.example". NULL addresses do not appear in the list: a comparison with NULL gives unknown (lesson 7), and WHERE drops it.
The first shortcut that comes to mind is ILIKE from lesson 5: it compares and ignores the difference between capital and small letters. Does it work?
Which of the two queries finds the student? Isabella's address is ISABELLA.POPESCU@STUDENTS.NORTHBRIDGE.EXAMPLE, and Felix's is felix.abara@students.northbridge.example (space at the end).
SELECT first_name FROM student WHERE email ILIKE 'isabella.popescu@students.northbridge.example'; SELECT first_name FROM student WHERE email ILIKE 'felix.abara@students.northbridge.example';
There is a second misunderstanding about TRIM: thinking that it also removes the spaces in the middle. TRIM looks only at the edges; the spaces inside the text stay where they are, however many there are. In the matching below, the quotes are written to show the spaces.
Match each expression with the result it produces.
For each row, pick its match from the list, then check.
TRIM(' Ada ')TRIM(' Ada Lee ')LOWER(' ADA ')LOWER(TRIM(' ADA '))The IT office wants to see the state of the list at a glance: how many students there are, how many have an address, how many have none, how many are dirty. COUNT(*) versus COUNT(column) from lesson 7 and CASE from lesson 8 work together here.
Example 2 (case): An X-ray of the list
SELECT COUNT(*) AS total, COUNT(email) AS with_email, COUNT(*) - COUNT(email) AS empty, SUM(CASE WHEN email <> LOWER(TRIM(email)) THEN 1 ELSE 0 END) AS dirty FROM student;
| total | with_email | empty | dirty |
|---|---|---|---|
| 120 | 111 | 9 | 17 |
(1 row)
What type of dirt do the 17 dirty addresses have? With CASE you give each dirty address a label and then group. Look at the spaces first: if the address is not equal to its own TRIM form, there is a space at the edge; if it is, the problem is in the letters.
SELECT CASE WHEN email <> TRIM(email) THEN 'space' ELSE 'uppercase' END AS kind, COUNT(*) AS addresses FROM student WHERE email <> LOWER(TRIM(email)) GROUP BY kind ORDER BY addresses DESC;
| kind | addresses |
|---|---|
| uppercase | 9 |
| space | 8 |
(2 rows)
An important point: after you run these queries, the table has not changed. The functions only show the fixed form in the result; the 17 addresses in the student table are still dirty. If you run Example 2 again, you find 17 again. The permanent fix is done with UPDATE in lesson 35.
Cleaning can also have a side effect: two different raw addresses can become the same address after cleaning (one is Ada@..., the other is ada@... ). Then two students would get the same email. You check this with COUNT(DISTINCT ...): COUNT(DISTINCT email) gives 111, and COUNT(DISTINCT LOWER(TRIM(email))) also gives 111. Because the number did not drop, cleaning does not make any two students share an address. In the cell below, extend the type breakdown yourself.
Try it now· not graded; doesn't affect progress
In the first task, three types appear: uppercase 9, trailing space 7, leading space 1. CASE tests the conditions in order, so the leading-space condition must be written first. The query in the second task returns 0 rows, which agrees with the COUNT(DISTINCT ...) check.
The second family extracts information from inside the text. The student number 202303001 actually carries three pieces of information side by side: the first four digits are the entry year (2023), the next two digits are the department code (03), and the last three digits are the sequence number within the department (001). To separate them:
LEFT(text, n) takes n characters from the start, and RIGHT(text, n) takes n characters from the end.SUBSTRING(text FROM start FOR length) cuts a piece from the middle. Counting starts at 1: FROM 5 means the fifth character.SPLIT_PART(text, separator, n) splits the text at the separator and gives the nth part. In an email, the part before the @ sign is the username, and the part after it is the domain.You should take the username from the clean address, not from the dirty one; otherwise you get a username like ISABELLA.POPESCU. So SPLIT_PART goes on the outside, and LOWER(TRIM(...)) goes inside it.
Example 3 (case): Information from the number and the address
SELECT student_no, LEFT(student_no, 4) AS entry_year, SUBSTRING(student_no FROM 5 FOR 2) AS department_code, RIGHT(student_no, 3) AS seq, SPLIT_PART(LOWER(TRIM(email)), '@', 1) AS username FROM student ORDER BY id;
| student_no | entry_year | department_code | seq | username |
|---|---|---|---|---|
| 202303001 | 2023 | 03 | 001 | anika.park |
| 202405001 | 2024 | 05 | 001 | anika.rivera |
| 202604001 | 2026 | 04 | 001 | felix.abara |
| 202304001 | 2023 | 04 | 001 | isabella.popescu |
| 202506001 | 2025 | 06 | 001 | felix.ortiz |
(first 5 of 120 rows)
Felix's and Isabella's usernames came out clean, because the part was taken from the clean address. For a student whose address is NULL, username is also NULL.
The part you extract can be used like any column; you can group it and count it. The number of students by entry year: the query SELECT LEFT(student_no, 4) AS entry_year, COUNT(*) FROM student GROUP BY entry_year ORDER BY entry_year; gives 21 for 2023, 35 for 2024, 35 for 2025, and 29 for 2026. The department code in the number also matches department_id one to one: every student with code 03 has department_id 3. A check like this shows whether the information packed inside the text can be trusted.
Now build a list sorted by username.
Put in order the query that returns the first 5 students alphabetically by username.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
You used LENGTH to catch the invisible space; length is needed for other jobs too. For example, if the student information screen has room for 25 characters for a course name, you want to know which names do not fit. POSITION(part IN text) gives the place of a part in the text: POSITION('@' IN 'ada@northbridge.example') returns 4, because @ is the fourth character. LENGTH('Müller') gives 6; accented letters count as one character each.
What does POSITION return if the part you search for is not in the text?
SELECT POSITION('#' IN 'ada@northbridge.example');
This is useful in address checks: WHERE POSITION('@' IN email) = 0 finds addresses with no @ sign, which means a broken format. There is no such address in the case.
Try it now· not graded; doesn't affect progress
The first query returns IND101 (38), MIS101 (35), CPR102 (29), GEN104 (29), CPR101 (28), SWE101 (27), SWE102 (27), IND203 (26), and PSY101 (26). With a threshold of 20, 17 courses appear. In the second task, the longest names are in the IND courses with an average of 26.8 characters, and the shortest are in the BUS courses with 17.6.
There is a trap in text that contains accented letters. Good news first: the PostgreSQL in your browser changes the case of accented letters correctly: UPPER('García') gives GARCÍA, and LOWER('MÜLLER') gives müller. The trap is a different one: an accent is part of the letter. 'García' and 'Garcia' are different strings, and ILIKE ignores the difference between capital and small letters, but not the difference between an accented and an unaccented letter.
The student table has 4 students whose last name is García. How many rows does this query return?
SELECT COUNT(*) FROM student WHERE last_name ILIKE 'garcia';
The result is 0. For a person, Garcia and García are the same name, but for the database they are not. This is why the school's email addresses are written without accents (salma.garcia@...): the name in the table is García, and the address is a different string. When you search names that people type, keep this in mind: a search for garcia will miss García. PostgreSQL has an extension called unaccent for this, but it is not available in the browser, so in this course you will use TRANSLATE instead (next section). From the same family, INITCAP(text) turns the first letter of each word into a capital: INITCAP('josé álvarez') gives José Álvarez.
The third family transforms text into another form. REPLACE(text, old, new) replaces every old part in the text with new; if the part is not found, the text stays as it is.
Example 4 (case): Shortening titles
SELECT title, REPLACE(title, 'Professor', 'Prof.') AS short, COUNT(*) AS people FROM instructor GROUP BY title ORDER BY people DESC, title;
| title | short | people |
|---|---|---|
| Assistant Professor | Assistant Prof. | 7 |
| Lecturer | Lecturer | 6 |
| Professor | Prof. | 4 |
| Associate Professor | Associate Prof. | 3 |
(4 rows)
Three of the four titles changed; Lecturer has no part to replace, so the text stayed the same. Two more helpers: concat_ws(separator, part1, part2, ...) joins the parts with the separator between them and skips NULL parts (concat_ws(' ', title, first_name, last_name) gives Associate Professor Diego Costa). LPAD(text, length, character) adds characters to the left of the text to fill it to a given length: LPAD('7', 3, '0') gives 007, a form like the last three digits of the student number.
Now the last step of the case: building suggested addresses. The school's pattern is first.last@students.northbridge.example. The first try is LOWER(first_name || '.' || last_name) || '@students.northbridge.example', and it works for the 9 students without an address. But for Salma García it gives salma.garcía@students.northbridge.example. The accent stays in the address, while all the school's addresses are written with unaccented letters. Here TRANSLATE(text, 'letters to find', 'replacements') helps: it is the letter-by-letter version of REPLACE, and it changes each letter in the first list to the letter at the same position in the second list. TRANSLATE(..., 'áéèíóúüñç', 'aeeiouunc') changes á to a, é and è to e, í to i, and so on, and gives salma.garcia@students.northbridge.example.
Try it now· not graded; doesn't affect progress
After the task, every suggestion matches the real address of that student. This pattern also agrees with the school's existing addresses: for all 111 students who have an address, the same expression gives exactly their cleaned address. Without TRANSLATE, only 92 of the 111 match. The 9 students without an address have no accented letters, so for them TRANSLATE changes nothing and the suggestions are jin.tanaka, kenji.novak, mohammed.cohen, tariq.patel, nikolai.haddad, marco.lindqvist, ali.chen, ivan.lindqvist, and nadia.santos with the school's domain.
The same way of thinking works on every dirty text column. A courier company's customer phone numbers were entered in three different forms, and one is empty. The query below reads from a small table written by hand with VALUES, like a subquery in FROM from lesson 21; it does not touch the case database.
Example 5 (outside the case): Putting phones into one form
SELECT id, phone, REPLACE(REPLACE(TRIM(phone), ' ', ''), '-', '') AS clean FROM (VALUES (1, ' 555 014 2001'), (2, '5550142001'), (3, '555-014-2001'), (4, NULL)) AS t(id, phone) ORDER BY id;
| id | phone | clean |
|---|---|---|
| 1 | 555 014 2001 | 5550142001 |
| 2 | 5550142001 | 5550142001 |
| 3 | 555-014-2001 | 5550142001 |
| 4 | NULL | NULL |
(4 rows)
Read from the inside out: TRIM removes the leading space, the inner REPLACE removes the spaces in the middle, and the outer REPLACE removes the hyphens. TRIM is not enough for the spaces in the middle, because it looks only at the edges; REPLACE(..., ' ', '') does that job. The last step is a check: a number in this format has 10 digits, so the condition LENGTH(clean) = 10 picks out the numbers whose format is confirmed.
How many of the cleaned forms of the three filled-in phones in Example 5 are 10 characters long?
SELECT LENGTH(REPLACE(REPLACE(TRIM(phone), ' ', ''), '-', '')) FROM (VALUES (' 555 014 2001'), ('5550142001'), ('555-014-2001')) AS t(phone);
Text functions work inside WHERE too, but in lesson 39 you will see that a condition with a function may not be able to use an index on a large table. The lasting fix is to store the data clean from the start and to correct the dirty rows with UPDATE (lesson 35).
Without a table, a few members of the same families on fixed text:
SELECT UPPER('García') AS upper_name, INITCAP('josé álvarez') AS title_case, LENGTH('Müller') AS length_chars, REPLACE('Assistant Professor', 'Professor', 'Prof.') AS short, LPAD('7', 3, '0') AS padded;
| upper_name | title_case | length_chars | short | padded |
|---|---|---|---|---|
| GARCÍA | José Álvarez | 6 | Assistant Prof. | 007 |
(1 row)
UPPER('García') turned the accented letter into its capital form Í, and INITCAP capitalized the first letter of each word and kept the accents.
Comparing dirty text without cleaning it. WHERE email = 'isabella.popescu@students.northbridge.example' returns no rows, because the address is stored in capital letters in the table. Adding only LOWER is not enough either: WHERE LOWER(email) = 'elena.singh@students.northbridge.example' still returns 0 rows, because Elena's address has a space at the end. When you compare text that may be dirty, apply both fixes together: WHERE LOWER(TRIM(email)) = 'elena.singh@students.northbridge.example' returns 1 row.
LENGTH shows the invisible space, email <> LOWER(TRIM(email)) finds the dirty rows; TRIM removes only the spaces at the start and the end.LEFT, RIGHT, SUBSTRING (counting from 1), and SPLIT_PART take parts of text, and POSITION gives the place of a part (0 if not found); take the part from clean text.REPLACE replaces a part, TRANSLATE converts letter by letter, concat_ws and LPAD reshape text. Functions do not change the table; an accent is part of a letter, so ILIKE 'garcia' does not find García.Next lesson: Text is done; dates are next: you will learn to calculate age, duration, and term.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
SELECT id, concat_ws(' ', title, first_name, last_name) AS display_name FROM instructor ORDER BY id LIMIT 3;
| id | display_name |
|---|---|
| 1 | Associate Professor Diego Costa |
| 2 | Lecturer Lucía Kowalski |
| 3 | Lecturer Rosa Bianchi |
(3 rows)
title || ' ' || first_name || ' ' || last_name gives the same result, but if one of the parts were NULL, the whole result would be NULL; concat_ws skips the NULL part.