Functions, Dates and Cleaning · Problem 15 of 118

Email Usernames

EasyFunctions, Dates and CleaningShop data

Return each customer's customer_id and the username of their email (everything before the @) for the customers with customer_id from 1 to 8, sorted by customer_id. Call the second column username.

Hint 1

INSTR(email, '@') gives the position of the @.

Hint 2

SUBSTR(text, 1, n) returns the first n characters.

Reference solution

SELECT customer_id,
       SUBSTR(email, 1, INSTR(email, '@') - 1) AS username
FROM customers
WHERE customer_id BETWEEN 1 AND 8
ORDER BY customer_id;

If the @ is at position 12, the username is the 11 characters before it, hence INSTR(...) - 1. Off-by-one errors are the classic trap of text functions: check your result by reading a row, and remember that positions start at 1, not 0.

Another way. Remove everything from the @ onward instead of copying what comes before it.

SELECT customer_id,
       REPLACE(email, SUBSTR(email, INSTR(email, '@')), '') AS username
FROM customers
WHERE customer_id BETWEEN 1 AND 8
ORDER BY customer_id;