Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Substring in MySQL criteria

Tags:

I'm trying to fetch all instances where the 1st letter of a person's first name is equal to P.

This is what I came up with, which doesn't return anything:

$sql="SELECT * FROM people WHERE SUBSTRING(FirstName,0,1) = 'P'";

Suggestions?

like image 402
Ian Avatar asked Mar 18 '11 04:03

Ian


People also ask

How do I select a part of a string in MySQL?

SUBSTRING() : function in MySQL is used to derive substring from any given string . It extracts a string with a specified length, starting from a given location in an input string. The purpose of substring is to return a specific portion of the string.

Can we use substring in where clause in SQL?

The SUBSTRING SQL function is very useful when you want to make sure that the string values returned from a query will be restricted to a certain length. In the following example, using the 'firstname' column, the last two characters are matched with the word 'on' using the SQL SUBSTRING function in the where clause.


1 Answers

The reason your expression doesn't work is that substring() positions are 1-based

Try either of these:

where FirstName like 'P%'

or

where substring(FirstName,1,1) = 'P'
like image 137
Jim Garrison Avatar answered Sep 23 '22 19:09

Jim Garrison