22 Votes

MySQL: Read out first 100 characters of a text field

Question by Compi | Last update on 2021-07-06 | Created on 2012-10-01

For a preview view, that should always display the beginning of a text, I need a MySQL query that always retrieves the first 100 characters of a field from a text column.

Of course, I can also do it like that: Reading out the entire text and then cutting off all unnecessary characters with PHP, but I think it's here better for the performance to read out only the characters you really need.

Does someone know a way to get that realized with MySQL?

ReplyPositiveNegative
2Best Answer2 Votes

Just use the MySQL function LEFT() for your project.

Here's an example:

SELECT LEFT(col, 100) FROM tab WHERE ...

LEFT() expects two parameters: the column that you want to retrieve (in this case "col") and the number of characters to be read out (here "100"). The rest of the query works like any other MySQL query, so you can also read out more values from other columns in the same query.

The opposite of the function LEFT() is the function RIGHT(). With this, the last x characters are read out in the same manner.

Caution: In the case, that you need on the same page both, the preview text and also the full text, you should read out the entire text field once to output it in its short and its long version. If you only need the short texts, the way with LEFT() will be the best.
Last update on 2021-07-06 | Created on 2012-10-03

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.