
SQL Challenge #98: How to Extract an Email Domain Using INSTR() and SUBSTR() in Oracle SQL
Sometimes, while working with employee or customer records, you may need to get the domain name separately from an email address.
For example:
- kailas@gmail.com → gmail.com
- rahul@yahoo.com → yahoo.com
Let's see how to do this using two simple Oracle SQL functions.
The Problem
You have an "employees" table containing email addresses.
You need to write a query that extracts everything after the "@" symbol and displays it in a separate column.
Input: employees
| emp_id | |
|---|---|
| 101 | kailas@gmail.com |
| 102 | rahul@yahoo.com |
| 103 | priya@outlook.com |
| 104 | amit@company.in |
| 105 | sneha@gmail.com |
Your Challenge
Write a query to:
- Find the position of "@" in each email.
- Extract everything after "@".
- Display the email and its domain.
- Keep the original table data unchanged.
Think about the query before looking at the solution!
Oracle SQL Solution
SELECT emp_id,
email,
SUBSTR(email, INSTR(email, '@') + 1) AS domain
FROM employees;
Expected Output
| emp_id | domain | |
|---|---|---|
| 101 | kailas@gmail.com | gmail.com |
| 102 | rahul@yahoo.com | yahoo.com |
| 103 | priya@outlook.com | outlook.com |
| 104 | amit@company.in | company.in |
| 105 | sneha@gmail.com | gmail.com |
How Does It Work?
Let's understand the two functions used in this query.
- INSTR()
"INSTR()" finds the position of a character in a string.
SELECT INSTR('kailas@gmail.com', '@')
FROM dual;
Output:
7
The "@" symbol is at position 7.
- SUBSTR()
"SUBSTR()" extracts characters from a given position.
SELECT SUBSTR('kailas@gmail.com', 8)
FROM dual;
Output:
gmail.com
- Using Both Functions Together
SUBSTR(email, INSTR(email, '@') + 1)
First, "INSTR()" finds the position of "@".
Then, we add 1 to start from the next character.
Finally, "SUBSTR()" extracts the remaining characters.
That's how we get the email domain in a single query.
Note: This query assumes that the email address contains an "@" symbol. Invalid email addresses should be checked separately.
Your Turn
Now try the opposite.
Suppose you have:
You want to extract only:
kailas
Which SQL function or combination of functions would you use?
Write your query in the comments. Let's see how you solve it!
Follow for more practical SQL questions and solutions.
Top comments (0)