Syntax error Fetch domain name by passing name in MySQL?

Fetch domain name by passing name in MySQL?



To fetch domain name by passing name in MySQL, you can use substring_index(). Let us first create a table −

mysql> create table DemoTable
   (
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserMailId varchar(200)
   );
Query OK, 0 rows affected (0.77 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(UserMailId) values('John9989@facebook.com');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(UserMailId) values('983773CS@yahoo.com');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable(UserMailId) values('Chris95@gmail.com');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+-----------------------+
| UserId | UserMailId            |
+--------+-----------------------+
|      1 | John9989@facebook.com |
|      2 | 983773CS@yahoo.com    |
|      3 | Chris95@gmail.com     |
+--------+-----------------------+
3 rows in set (0.00 sec)

Following is the query to fetch domain name by passing name in MySQL.

mysql> select
   UserId,UserMailId,
   substring_index(substring_index(UserMailId, '@', -1), '.', 1) AS `Domain_Name`
   from DemoTable;

This will produce the following output. Here, domain name is fetched −

+--------+-----------------------+-------------+
| UserId | UserMailId            | Domain_Name |
+--------+-----------------------+-------------+
|      1 | John9989@facebook.com | facebook    |
|      2 | 983773CS@yahoo.com    | yahoo       |
|      3 | Chris95@gmail.com     | gmail       |
+--------+-----------------------+-------------+
3 rows in set (0.01 sec)
Updated on: 2019-07-30T22:30:26+05:30

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements