How to Extract a Substring From a String in MySQL

Last updated 2 years ago

...

Extract a Substring From a String in MySQL

Method 1.
To exhibit the initial seven characters of each email, access the email column situated in the users table.

idnameemaildate
1Oliveroliver17@gmail.com2023-05-05
2Islaisla-li@gmail.com2023-05-05
3Hudsonhudsonmel@yahoo.com2023-05-05
4Georgegeorge@rediffmail.com2023-05-05

 

SELECT email, SUBSTRING(email, 1, 7) AS sub_email FROM users;

Output:

emailsub_email
oliver17@gmail.comoliver1
isla-li@gmail.comisla-li
hudsonmel@yahoo.comhudsonm
george@rediffmail.comgeorge@

 

Another syntax with same result.

SELECT email, SUBSTRING(email FROM 1 FOR 7) AS sub_email FROM users;

Output:

emailsub_email
oliver17@gmail.comoliver1
isla-li@gmail.comisla-li
hudsonmel@yahoo.comhudsonm
george@rediffmail.comgeorge@

 

Use the SUBSTRING() function, which requires three arguments. The initial argument denotes either the string or the column name being referenced. The second argument specifies the starting index of the character where the substring should begin. The third argument represents the length of the substring desired.

 

Method 2.

The segment of characters encompassing indices 2 through 6 (inclusive) is what you wish to exhibit.

SELECT email, SUBSTRING(email, 2, 5) AS sub_email FROM users;

Output:

emailsub_email
oliver17@gmail.comliver
isla-li@gmail.comsla-l
hudsonmel@yahoo.comudson
george@rediffmail.comeorge

 

Another syntax

SELECT email, SUBSTRING(email FROM POSITION('@' IN email)) AS sub_email FROM users;

Output:

emailsub_email
oliver17@gmail.com@gmail.com
isla-li@gmail.com@gmail.com
hudsonmel@yahoo.com@yahoo.com
george@rediffmail.com@rediffmail.com

 


Avoid Dividing by Zero in...

The initial method 1 involves utilizing the NULLIF() function, which requires two numerical inputs....

Read It

An Introduction To CSS Pr...

CSS or Cascading Style Sheets have become a really popular programming language in recent times and...

Read It



----Advertisement----