SELECT part of a field

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
traffic
Forum Newbie
Posts: 17
Joined: Fri May 23, 2003 1:18 pm

SELECT part of a field

Post by traffic »

Hello...

I have a field in my database that is a 'text' field - post_text...

I want to be able to select just the first (500) characters in the field - but, can't seem to find any documentation for this...

Any help would be appreciated...


...
yum-jelly
Forum Commoner
Posts: 98
Joined: Sat Oct 29, 2005 9:16 pm

Post by yum-jelly »

Have a look at MySQL String function... A little searching never hurt, :wink:


SUBSTRING()

Code: Select all

SELECT SUBSTRING(text_column_name, start_position, end_position) AS text FROM articles WHERE article_id = some_id;
Where as....

text_column_name = post_text <- your column name

start_position = where you want to start the string <- would be * 0 * if you want the first five hundred characters

end_position = where you want to end the string <- would be * 500 * if you want the first five hundred characters (number of character to grab [len])

yj
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: SELECT part of a field

Post by RobertGonzalez »

traffic wrote:Hello...

I have a field in my database that is a 'text' field - post_text...

I want to be able to select just the first (500) characters in the field - but, can't seem to find any documentation for this...

Any help would be appreciated...


...
Use the MySQL LEFT() function, like this...

Code: Select all

$sql = "SELECT LEFT('fieldname', 500) FROM table";
Grim...
DevNet Resident
Posts: 1445
Joined: Tue May 18, 2004 5:32 am
Location: London, UK

Post by Grim... »

If you want to do it with PHP (this is the PHP forum, after all) get the field as normal, then use

Code: Select all

$post_text = substr($post_text, 0, 500);
However, using SQL will be a tiny bit faster, and is the better way to do it.
Post Reply