// strings reference

SQL RIGHT function

Returns the rightmost n characters of a string: the tail of a filename, the last four digits of a card, the suffix of a code.

Категория
Strings
Returns
string
In this category
9 of 172

Синтаксис

RIGHT(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 RIGHT(); use SUBSTR(string, -n)
Oracle Different name or syntax no RIGHT(); use SUBSTR(string, -n)

Примеры

SQL Server

-- same on PostgreSQL and MySQL
SELECT RIGHT('report_2026.csv', 3) AS ext;  -- csv

SQLite

SELECT SUBSTR('report_2026.csv', -3) AS ext;  -- csv

Oracle

SELECT SUBSTR('report_2026.csv', -3) AS ext FROM dual;  -- csv

Полезно знать

  • n larger than the string returns the whole string on the engines that have RIGHT.
  • The SQLite and Oracle stand-in uses a negative start: SUBSTR(string, -n). They differ when n is longer than the string: SQLite returns the whole string, Oracle returns NULL.
  • RIGHT assumes a fixed-width suffix. RIGHT(file, 3) is wrong for 'data.json'; for variable-width pieces use SPLIT_PART or a regex.

Questions about RIGHT

Does SQLite have a RIGHT function?

No. SUBSTR(string, -n) returns the last n characters and is the idiomatic SQLite replacement, since a negative start counts from the end.

How do I get the last 4 characters of a string?

RIGHT(s, 4) on SQL Server, PostgreSQL and MySQL; SUBSTR(s, -4) on SQLite and Oracle. On Oracle, SUBSTR(s, -4) is NULL when s is shorter than 4 characters.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

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.