What is the shortest and/or efficient SQL statement to sort a table with a column of email address by it's DOMAIN name fragment?
That's essentially ignoring whatever is before "@" in the email addresses and case-insensitive. Let's ignore the internationalized domain names for this one.
Target at: mySQL, MSSQL, Oracle
Sample data from TABLE1
id name email ------------------------------------------ 1 John Doe [email protected] 2 Jane Doe [email protected] 3 Ali Baba [email protected] 4 Foo Bar [email protected] 5 Tarrack Ocama [email protected]
Order By EmailSELECT * FROM TABLE1 ORDER BY EMAIL ASC
id name email ------------------------------------------ 3 Ali Baba [email protected] 4 Foo Bar [email protected] 2 Jane Doe [email protected] 1 John Doe [email protected] 5 Tarrack Ocama [email protected]
Order By DomainSELECT * FROM TABLE1 ORDER BY ?????? ASC
id name email ------------------------------------------ 5 Tarrack Ocama [email protected] 3 Ali Baba [email protected] 1 John Doe [email protected] 2 Jane Doe [email protected] 4 Foo Bar [email protected]
EDIT:
I am not asking for a single SQL statement that will work on all 3 or more SQL engines. Any contribution are welcomed. :)
LENGTH(email) - (INSTR(email, '@') + 1) - LENGTH(SUBSTRING_INDEX(email,'. ',-1)) will get the length of the domain minus the TLD (.com, . biz etc. part) by using SUBSTRING_INDEX with a negative count which will calculate from right to left.
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.
Try this
Query(For Sql Server):
select * from mytbl
order by SUBSTRING(email,(CHARINDEX('@',email)+1),1)
Query(For Oracle):
select * from mytbl
order by substr(email,INSTR(email,'@',1) + 1,1)
Query(for MySQL)
pygorex1 already answered
Output:
id name email
5 Tarrack Ocama [email protected]
3 Ali Baba [email protected]
1 John Doe [email protected]
2 Jane Doe [email protected]
4 Foo Bar [email protected]
For MySQL:
select email, SUBSTRING_INDEX(email,'@',-1) AS domain from user order by domain desc;
For case-insensitive:
select user_id, username, email, LOWER(SUBSTRING_INDEX(email,'@',-1)) AS domain from user order by domain desc;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With