Retrieve first 40 characters of a text field in MySQL?

MySQLMySQLi Database

To get the first 40 characters from a text field, use LEFT() function from MySQL. The syntax is as follows −

SELECT LEFT(yourColumnName,40) as anyVariableName from yourTableName;

To understand the above concept, let us create a table. The query to create a table is as follows −

mysql> create table retrieveFirst40Characters
   −> (
   −> AllWords text
   −> );
Query OK, 0 rows affected (0.59 sec)

Now you can insert some record in the table with the help of insert command. The query is as follows −

mysql> insert into retrieveFirst40Characters values('This is a query demo to extract a forty characters from a text
'> field,you can use left function to get forty characters');
Query OK, 1 row affected (0.32 sec)

Display all records from table using select statement. The query is as follows −

mysql> select *from retrieveFirst40Characters;

The following is the output −

+------------------------------------------------------------------------------------------------------------------------+
| AllWords                                                                                                               |
+------------------------------------------------------------------------------------------------------------------------+
| This is a demo text displayed in a table for our example                                                               |
+------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Here is the query to extract first 40 characters from a text field −

mysql> select left(AllWords,40) as Retrieve40Characters from retrieveFirst40Characters;

The following is the output displaying first 40 characters −

+------------------------------------------+
| Retrieve40Characters                     |
+------------------------------------------+
| This is a demo text displayed in a table |
+------------------------------------------+
1 row in set (0.03 sec)
raja
Published on 11-Jan-2019 11:36:42
Advertisements