169

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?

span
  • 5,405
  • 9
  • 57
  • 115
zeroweb
  • 2,612
  • 4
  • 22
  • 34

3 Answers3

351

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

Muhammad Hani
  • 8,476
  • 5
  • 29
  • 44
65
SELECT SUBSTRING(subject, 1, 10) FROM tbl
Rajesh Paul
  • 6,793
  • 6
  • 40
  • 57
  • 1
    I feel like this is the more complete answer, since `LEFT` may not address specifics (yes, like those raised by the OP) dealing with extractions that need to start mid-string. – d8aninja Oct 17 '18 at 20:28
12

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.

Steve
  • 3,673
  • 1
  • 19
  • 24
  • 6
    A sample would have been a bit more helpful. – Rocco The Taco Mar 11 '14 at 14:46
  • 6
    @RoccoTheTaco I totally disagree - also your down vote is very harsh. read `http://stackoverflow.com/questions/how-to-ask` the very first point is `Have you thoroughly searched for an answer before asking your question?`. This question is so easily answered by a simple and quick Google search. I didn't just want to give the OP the answer I wanted to show them HOW to find the answer - *much* more useful in my opinion. – Steve Mar 11 '14 at 16:42
  • 13
    I understand what @Steve is saying (makes sense) but I came here from Google. Yes, the original question was lazy but the fact that I don't have to go somewhere else helped me. It's also nice that SO is building up a library of answers to simple questions like these. Also equals more advertising $ for SO. – sterfry68 Dec 31 '14 at 19:49