Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first part from the Postcode?

Tags:

mysql

Using MySQL how to grab first part of the data.postcode field?

For example:

M40 1JY
M8 8NW

I want to display like this:

M40
M8
like image 220
I'll-Be-Back Avatar asked May 07 '26 11:05

I'll-Be-Back


2 Answers

select substring(postcode, 1, locate (' ', postcode) - 1) from data;

locate (' ', postcode) returns the position of the space (), the first input, out of the second input (your column), you don't want to display the space so subtract 1 from this number.

substring(data, start, length) takes the substring of the data (your column) from the number of start, you want to start at the beginning, so this is 1, and displays the number of letters you enter in length, this is the result of locate.

like image 175
Simulant Avatar answered May 10 '26 03:05

Simulant


The SUBSTRING_INDEX(str,delim,count) function is what you need. This function return the substring from string str before count occurrences of the delimiter delim. You can go the this link for more details. http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index

For your problem,

SELECT SUBSTRING_INDEX(postcode, ' ', 1) from YourTable; 

will return

M40
M8
like image 39
Chong Tang Avatar answered May 10 '26 01:05

Chong Tang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!