Search code examples
sqlsqliteemulationpadding

How to emulate LPAD/RPAD with SQLite


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:


Solution

  • A simpler version of @user610650's solution, using hex() instead of quote(), and works with string padding in addition to char padding:

    X = padToLength
    Y = padString
    Z = expression
    
    select
        Z ||
        substr(
            replace(
                hex(zeroblob(X)),
                '00',
                Y
            ),
            1,
            X - length(Z)
        );