Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite - reverse string function

Tags:

sqlite

Is there a function for reversing string in SQLite? I'm unable to find anything in the documentation.

like image 336
Martin Vseticka Avatar asked Oct 19 '11 19:10

Martin Vseticka


People also ask

What are the three arguments for the substr () function in SQLite?

SQLite substr() returns the specified number of characters from a particular position of a given string. A string from which a substring is to be returned. An integer indicating a string position within the string X. An integer indicating a number of characters to be returned.

What is Substr in SQLite?

The SQLite substr function returns a substring from a string starting at a specified position with a predefined length.

How do I find the length of a string in SQLite?

Since SQLite strings do not normally contain NUL characters, the length(X) function will usually return the total number of characters in the string X. For a blob value X, length(X) returns the number of bytes in the blob.

Which of the following function is used to get the version of SQLite?

SQLite sqlite_version function returns the version of the SQLite library.


2 Answers

There is no builtin function for that. You can add custom function, like in this example in Python:

import sqlite3
conn = sqlite3.connect("")

conn.create_function("strrev", 1, lambda s: s[::-1])

cur = conn.cursor()
cur.execute(r''' SELECT strrev('hello, world') ''')
print(cur.fetchone()[0]) #dlrow ,olleh
like image 98
hamstergene Avatar answered Oct 03 '22 21:10

hamstergene


Using a common table expression it is possible to reverse a string in SQLite.

WITH reverse(i, c) AS (
    values(-1, '')
    UNION ALL SELECT i-1, substr('dlrow olleh', i, 1) AS r FROM reverse
    WHERE r!=''
) SELECT group_concat(c, '') AS reversed FROM reverse;

Returns hello world.

like image 40
user1461607 Avatar answered Oct 03 '22 20:10

user1461607