Wednesday, April 24, 2013

MySQL - extract domain from url

Let's say you have a table called Post that has a column called "url" and you want to extract the domain component and save it in a new column called "domain".
update Post set domain = (select (SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX((url), '://', -1),'/',1),'www.', -1)))
Note that the above will not get rid of the subdomain if it's not "www". For example, if the url is "blog.developer24hours.com/mysql-extract-domain-from-url", then the above SQL will give you "blog.developer24hours.com".

2 comments:

  1. One big problem: what if the domain is:

    http://google.com

    Without trailing slash?

    ReplyDelete
  2. One big problem: what if the domain is:

    http://google.com

    Without trailing slash?

    ReplyDelete