Lesson

MySQL LEFT() Function

10 min reading
Free Course

MySQL LEFT() Function

The LEFT() function returns a specified number of characters from the start of a string. It gives you a concise alternative to SUBSTRING(str, 1, len) when slicing prefixes.

Syntax

LEFT(str, len)
  • str: The source string or column.
  • len: Number of leading characters to return.
  • Return value: Substring of up to len characters, or NULL if either argument is NULL.

LEFT() counts logical characters rather than bytes, so accented letters and emoji never split mid-character under utf8mb4.

Practical Example

In demo_orders, every order_code starts with a two-letter country prefix such as 'US-2026-881'. You can group daily volume by region using LEFT().

SELECT
    order_id,
    order_code,
    LEFT(order_code, 2) AS region_code,
    LEFT(order_code, 7) AS region_year
FROM demo_orders
ORDER BY order_id;
order_id order_code region_code region_year
101 US-2026-881 US US-2026
102 DE-2026-412 DE DE-2026
103 JP JP JP
104 NULL NULL NULL

Notice row 103: when len (7) exceeds the string's length (2), MySQL returns the entire string 'JP' without padding or throwing an error.

Common Mistakes & NULL Behavior

  • Zero or negative lengths return empty string: Calling LEFT('US-2026', 0) or LEFT('US-2026', -3) returns '', not an error and not characters from the right.
  • NULL propagation: If str or len is NULL, LEFT() returns NULL.
  • Variable-length prefixes: LEFT() works best for fixed-width codes. When prefix widths vary before a delimiter like '-', pair SUBSTRING_INDEX(order_code, '-', 1) instead.

Frequently Asked Questions

What is the difference between LEFT(str, n) and SUBSTRING(str, 1, n)?

They produce identical results for positive lengths. LEFT() is shorter and communicates intent clearly when reading prefixes.

Does LEFT() count spaces at the beginning of a string?

Yes. A leading space counts as one character, so LEFT(' ABC', 2) returns ' '.

How do I extract characters from the end of a string instead?

Use RIGHT(str, len) for fixed-width suffixes or SUBSTRING(str, -len).

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum