MySQL Select Query - Get only first 10 characters of a value

MysqlSqlSelect

Mysql Problem Overview


Ok, so here is the issue.

I have a table with some columns and 'subject' is one of the columns. I need to get the first 10 letters from the 'subject' field no matter the 'subject' field contains a string with 100 letters.

For example,

Table - tbl. Columns - id, subject, value.

SQL Query:

SELECT subject FROM tbl WHERE id ='$id';

The result I am getting is, for example

> Hello, this is my subject and how are you

I only require the first 10 characters

> Hello, thi

I can understand that I can remove the rest of the characters using php substr() but that's not possible in my case. I need to get the excess characters removed by MySQL. How can this be done?

Mysql Solutions


Solution 1 - Mysql

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

Solution 2 - Mysql

SELECT SUBSTRING(subject, 1, 10) FROM tbl

Solution 3 - Mysql

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzerowebView Question on Stackoverflow
Solution 1 - MysqlMuhammad HaniView Answer on Stackoverflow
Solution 2 - MysqlRajesh PaulView Answer on Stackoverflow
Solution 3 - MysqlSteveView Answer on Stackoverflow