30

I'm executing a SELECT query on a table in MySQL using the command-line interface (not a GUI client):

SELECT * FROM blog_entry;

One of blog_entry's fields is of type 'longtext' and is such a long piece of text that when the result is displayed in my terminal the display of rows takes more than one line. This causes an ugly mess of a display, where columns aren't easily visible. What technique can I use in my SELECT query that would limit the number of characters displayed for each field so that the printed row results don't overflow to new lines?

halfer
  • 18,701
  • 13
  • 79
  • 158
maxm
  • 4,407
  • 7
  • 25
  • 32

4 Answers4

47

Use MySQL's SUBSTRING function, as described in the documentation. Like:

SELECT SUBSTRING(`text`, 1, 100) FROM blog_entry;

To select first 100 chars.

Oldskool
  • 32,791
  • 7
  • 50
  • 64
27

You can use the LEFT() function to get only the first characters:

SELECT LEFT(LongField, 20) AS LongField_First20chars
FROM ...
ypercubeᵀᴹ
  • 105,605
  • 14
  • 160
  • 222
  • 5
    @ValentinHeinitz ? The question is about MySQL, not SQLite. SQLite has `substr()` function, you can use it like in Oldskool's answer. – ypercubeᵀᴹ Jan 22 '16 at 12:52
  • You don't really need the `as LongField_First20chars` unless you want to make it easier to use from a program. – poolie May 08 '16 at 00:48
  • 1
    @poolie of course you don't. But it's good practice to have an alias in the returned columns. – ypercubeᵀᴹ May 08 '16 at 07:47
12

The best way to clean up the readability of the results from a query in your terminal window is to use the mysql pager, not modifying your query as that can be too cumbersome.

  1. Set the pager:

    mysql> pager less -S

  2. Do your query:

    mysql> SELECT * FROM ...

This will put your results in a more readable format. You can use your arrow keys to page up and down and left and right to see the full table. Just press Q to get out of pager mode for that query, and then just run

mysql> pager more

to return to the normal output river if you want.

AgmLauncher
  • 6,486
  • 5
  • 36
  • 60
3
Select Cast(theLongTextField As VarChar(100)) From blogEntry
Bassam Mehanni
  • 14,186
  • 2
  • 30
  • 41