SQL LEFT function
Returns the leftmost n characters of a string. SQL Server, PostgreSQL and MySQL have it; SQLite and Oracle use SUBSTR instead.
- Категория
- Strings
- Returns
string- In this category
- 8 of 172
Синтаксис
LEFT(string, n)
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Да | Supported under this name. |
| PostgreSQL | Да | Supported under this name. |
| MySQL | Да | Supported under this name. |
| SQLite | Different name or syntax | no LEFT(); use SUBSTR(string, 1, n) |
| Oracle | Different name or syntax | no LEFT(); use SUBSTR(string, 1, n) |
Примеры
SQL Server
-- same on PostgreSQL and MySQL
SELECT LEFT('2026-08-01', 4) AS year; -- 2026
SQLite
SELECT SUBSTR('2026-08-01', 1, 4) AS year; -- 2026
Oracle
SELECT SUBSTR('2026-08-01', 1, 4) AS year FROM dual; -- 2026
Полезно знать
- If n is longer than the string, LEFT returns the whole string, with no padding and no error.
- Negative n differs: SQL Server raises 'Invalid length parameter', MySQL returns '', and PostgreSQL returns all but the last |n| characters, so LEFT('abc', -1) is 'ab'.
- The SQLite and Oracle stand-in is SUBSTR(string, 1, n), which behaves the same for positive n.
Questions about LEFT
Does Oracle have a LEFT function?
No. Use SUBSTR(string, 1, n), which returns the same first n characters.
What happens if n is bigger than the string?
LEFT returns the entire string. It never pads, so LEFT(code, 3) on a two-character code gives two characters back.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Excluding rows: NOT IN vs NOT EXISTS vs LEFT JOIN Dialect comparison
- Column-prefix indexes in every SQL dialect Dialect comparison
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.