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.
Related on SQLly
- Extract the domain from an email address in SQL Snippet
- Extract trailing digits from a string in SQL Snippet
- Mask payment card numbers in SQL (show last 4) Snippet
- Mask an email address in SQL for display Snippet
- Mask names in query results Snippet
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.