Inserting a number as a String into a Text column and SQLite stills removes the leading zero Inserting a number as a String into a Text column and SQLite stills removes the leading zero sqlite sqlite

Inserting a number as a String into a Text column and SQLite stills removes the leading zero


Double-check your database schema. As documented on Datatypes in SQLite Version 3, the column type name affects how values are processed before being stored.

Here's a Python program to demonstrate, using an in-memory database:

import sqlite3db = sqlite3.connect(':memory:')val = "0796";db.execute('CREATE TABLE test (i INTEGER, r REAL, t TEXT, b BLOB);')db.execute('INSERT INTO test VALUES (?, ?, ?, ?);', (val, val, val, val))res = db.execute('SELECT * FROM test');print '\t'.join([x[0] for x in res.description])for row in res.fetchall():    print '\t'.join([repr(x) for x in row])

The output is:

i    r      t       b796  796.0  u'0796' u'0796'

So, it looks like your column is actually an integer type. Take a look at the schema definition (sqlite3 database.db .schema works from the command line), look at the documentation again, and make sure you are using one of type names that map to TEXT affinity. Unknown type names get INTEGER affinity.

In my own case, I was using 'STR', which ends up with the default INTEGER affinity. I changed it to 'TEXT', and SQLite started respecting my leading zeros.


Use single quotes around the number, (i.e., '079674839') if it is anywhere in inline sql code. Also, if you're doing this programatically, make sure that you are not going through a numeric conversion.