Zabs
Zabs

Reputation: 14142

Remove all but first character of a string in MySQL query

I am trying to run a query directly in MySQL to run through a series of records and replace the value of field with just the field character of the row.

e.g based on a column called formname

row 1 - Renault
row 2 - Citreon
row 3 - Jaguar

That will return..

row 1 - R
row 2 - C
row 3 - J

I can do this easily using native PHP functions but unsure how to do this using a native MYSQL function SUBSTR function?

Upvotes: 3

Views: 2678

Answers (2)

Linger
Linger

Reputation: 15048

To get this with the SUBSTR() function like you are asking for, you would use:

SELECT Field1, SUBSTR(field2, 1, 1) 
FROM MyTable

The function definition: SUBSTR(str,pos,len)

Upvotes: 1

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

You can use left

update table
set column = left(column,1)

or for select you can write

select col1,left(col2,1)
from table

Demo

Upvotes: 4

Related Questions