How to sort domain names in MySQL?


To sort domain names, use the ORDER BY SUBSTRING_INDEX(). Let us first create a table −

mysql> create table DemoTable670(DomainName text);
Query OK, 0 rows affected (0.77 sec)

Insert some records in the table using insert command. Here, we are inserting domain names −

mysql> insert into DemoTable670 values('www.facebook.com');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable670 values('www.google.com');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable670 values('www.amazon.com');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable670;

This will produce the following output −

+------------------+
| DomainName       |
+------------------+
| www.facebook.com |
| www.google.com   |
| www.amazon.com   |
+------------------+
3 rows in set (0.00 sec)

Following is the query to sort domains in MySQL −

mysql> select *from DemoTable670 order by SUBSTRING_INDEX(DomainName, '.', -2),SUBSTRING_INDEX(DomainName, '.', 2);

This will produce the following output −

+------------------+
| DomainName       |
+------------------+
| www.amazon.com   |
| www.facebook.com |
| www.google.com   |
+------------------+
3 rows in set (0.00 sec)

Updated on: 26-Aug-2019

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements