I'm curious about how to emulate RPAD and LPAD functions for SQLite, formally, in the most general way. The goal is to be able to do
LPAD(column, character, repeat)
RPAD(column, character, repeat)
For non-constant table columns column
, character
, repeat
. If character
and repeat
were known constants, then this would be a good, viable solution:
But what if the above should be executed like this:
SELECT LPAD(t.column, t.character, t.repeat) FROM t
SELECT LPAD(t.column, some_function(), some_other_function()) FROM t
SELECT LPAD(t.column, :some_bind_variable, :some_other_bind_variable) FROM t
How could this LPAD
function be generally emulated? I'm lost with the possibilities:
A related question:
A simpler version of @user610650's solution, using hex() instead of quote(), and works with string padding in addition to char padding:
I absolutely have no experience with SQLite, actually my time of interacting with SQLite3 db less then three days only. So I am not sure my findings could help anything to your requirement.
I am playing with some fun project of having all possible 11 digit phone number (3 digit operator prefix + 8 digit subscriber number). My target was to create some kind of database with minimum possible storage resource but must have to cover every possible number on database. So I created one table for 8 digit subscriber and another table contain 3 digit company prefix. Final number will come up on view joining two table data. Let me focus on LOAD Problem. As subscriber table column is INT, it is 0 to 99999999 individual record. Simple join fail for subscriber number having less then 10000000 ; any subscribers subscription id number valued under 10000000 shows up XXXprefix+11 where expecting XXX000000+11.
After failing with LPAD/RPAD on SQLite, I found "SUBSTR"!
Have a look on query bellow :
Now I think you can use SUBSTR for your LPAD/RPAD needs.
Cheers!
A JDBC/custom functions approach (may not be suitable in your exact case, but might be able to be adapted). Uses inspiration from SqliteJDBC Custom Functions and the rightPad and leftPad functions from Apache commons.lang.StringUtils:
(Untested, off the cuff, doesn't handle nulls, etc, but should outline the idea...)
Maybe like this:
LPAD(@orig_text, @padding_char, @padding_length)
:RPAD(@orig_text, @padding_char, @padding_length)
:Here's more nastiness for you:
RPAD (for LPAD, Z is concatenated after instead):
Examples:
Sqlite is meant to be quite lightweight, so I have to disagree somewhat with your comment about being "surprised" by the lack of functionality. However, I agree that there should be a simpler way to do padding, if only because the
trim
functions exist.Copied from http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/