Explain Codes LogoExplain Codes Logo

Mysql Select Query - Get only the first 10 characters of a value

sql
database-performance
string-manipulation
mysql-functions
Anton ShumikhinbyAnton Shumikhin·Mar 1, 2025
TLDR

Get the first 10 characters from a MySQL column using LEFT(column_name, 10):

-- It's like asking for "just 10" at a deli SELECT LEFT(column_name, 10) FROM table_name;

Choose wisely: LEFT vs SUBSTRING

We just used the LEFT() function, but the SUBSTRING() function is also a good contender for this task:

-- Yeah, "SUBSTRING ", you also get a slice! SELECT SUBSTRING(column_name, 1, 10) FROM table_name;

The choice between LEFT and SUBSTRING boils down to your particular requirements.

Speedy results: DB Layer over Application Layer

Do the character slicing with MySQL's LEFT() or SUBSTRING() and avoid PHP's substr(). It's faster and avoids getting your app layer's hands dirty processing strings.

Gracefully handling edge cases

Dealing with NULL or short values

Surprise, surprise! In case of values that are NULL or shorter than 10 characters, LEFT() and SUBSTRING() handle them like a boss, returning the original value.

Performance Proficiency

If you're dealing with lots of data, use substring functions in your SQL query. It keeps your DB resources and server happy, and gets you quick results.

Additional considerations

Writing clean code

Using MySQL for all the string work leaves your PHP code all spruced up and easier to read and maintain.

Flexibly using LEFT and SUBSTRING

LEFT() and SUBSTRING() are not just for static values. They can work dynamically within stored procedures or when used with other SQL functions, enabling complex manipulations.

Adapting to your own database structure

Don't forget to change the table and column names in the example query to match your actual database structure.

Going beyond LEFT and SUBSTRING

Once you're comfortable with these methods, feel adventurous and explore more advanced MySQL documentations on functions like LOCATE(), INSTR(), CHAR_LENGTH(), and CONCAT().