Limit length of longtext field in SELECT results
Asked Answered
M

4

36

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?

Madian answered 11/2, 2012 at 23:45 Comment(0)
Z
61

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

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

To select first 100 chars.

Zoltai answered 11/2, 2012 at 23:48 Comment(2)
I found that the single inverted commas around 'text' was not required if 'text' is a field nameBurck
Are there (dis-)advantages compared to LEFT()?Disturbing
T
33

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

SELECT LEFT(LongField, 20) AS LongField_First20chars
FROM ...
Trieste answered 11/2, 2012 at 23:48 Comment(3)
You don't really need the as LongField_First20chars unless you want to make it easier to use from a program.Fries
@Fries of course you don't. But it's good practice to have an alias in the returned columns.Coeliac
Quote the AS clause for pretty column names: "LongField (short view)".Mcneely
M
15

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.

Mallina answered 15/1, 2014 at 17:49 Comment(2)
Seems like -S would chop the whole line, not each column.Evanevander
Rick, it does seem to chop (needed) columns in an intelilgent manner (IDK how)Springhalt
M
5
Select Cast(theLongTextField As VarChar(100)) From blogEntry
Manmade answered 11/2, 2012 at 23:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.