REVERSE() in SQL

Returns a string value in a reversed order (characters displayed in reverse order).

Syntax

REVERSE(string)
Return type
VARCHAR (or equivalent string type in the respective DBMS)

REVERSE() Function Example

SELECT REVERSE('Hello World');
-- Output: 'dlroW olleH'

What is REVERSE() in SQL?

The REVERSE() function in SQL returns a string with its characters displayed in reverse order. It is commonly used for text manipulation, data transformation, and pattern matching tasks. This function is supported in databases like SQL Server, MySQL, and PostgreSQL, and is often used for checking palindromes, reversing IDs, or decrypting obfuscated text. Since REVERSE() does not alter the original data but instead returns a modified string, it is useful in queries that require reordering of textual content dynamically.

Parameters:

  • string: The input string to be reversed

Example Use Cases:

-- Check for palindromes

SELECT word FROM words WHERE word = REVERSE(word);
-- Output:
word
--------
radar
level
noon
madam
stats

-- Create reverse username

SELECT username, REVERSE(username) AS reverse_name FROM users;
-- Output:
username    reverse_name
----------  ------------
john123     321nhoj
sarah89     98haras
mike2024    4202ekim
alex555     555xela
sam1990     0991mas

-- Reverse product codes

SELECT REVERSE(product_code) AS reversed_code FROM products;
-- Output:
reversed_code
------------
54321-CBA
98765-XYZ
24680-DEF
13579-MNO
86420-PQR

Notes:

  • Behavior: Reverses all the characters, including the spaces, treats Unicode characters as single units, and returns an empty string if the input is empty.

  • Performance Considerations: Simple operation, generally efficient.

  • Version Info: Basic string function available in most DBMS

  • Deprecated/Recommended Alternatives: None

Error Handling:

  • Error: Returns NULL if input is NULL

  • Recommendation: Use COALESCE if NULL handling needed

Supported Databases:

DBMS
Function / Syntax
Example
Behavior with NULL
MySQL

REVERSE()

REVERSE('Hello')    

Returns NULL

PostgreSQL

REVERSE()

REVERSE('Hello')

Returns NULL

SQL Server

REVERSE()

REVERSE('Hello')

Returns NULL

SQLite

REVERSE()

REVERSE('Hello')

Returns NULL

BigQuery

REVERSE()

REVERSE('Hello')

Returns NULL

Snowflake

REVERSE()

REVERSE('Hello')

Returns NULL

Athena

REVERSE()

REVERSE('Hello')

Returns NULL

Related Functions:

One place for all your queries,
directly on your SQL editor