0

When I run an incorrect statement in Python I do not get any error or warning. The statement looks like this:

CREATE TABLE mystery_table(id mystery_type)

As you see, I'm using here an incorrect data type mystery_type, still table is created and when I run

SELECT name FROM sqlite_master where type = 'table'

I get a list of tables with mystery_table among them. So, why is that? Why is it possible to run some rubbish statement and get some result?? Thanks! PS. I run all this commands not in sqlite3 prompt, but through Python.

1 Answer 1

5

For what it's worth, this is also possible in the sqlite3 console.

Based on the sqlite3 FAQs, sqlite doesn't appear to strictly enforce the type constraints you apply when creating the table, but instead just uses them to format data when you retrieve it later:

[SQLite] does not enforce data type constraints. Data of any type can (usually) be inserted into any column. [...] But SQLite does use the declared type of a column as a hint that you prefer values in that format. So, for example, if a column is of type INTEGER and you try to insert a string into that column, SQLite will attempt to convert the string into an integer. If it can, it inserts the integer instead. If not, it inserts the string. This feature is called type affinity.

The documentation on type affinity suggests that it applies a data type of NUMERIC if it doesn't recognize the type you supply:

The affinity of a column is determined by the declared type of the column, according to the following rules in the order shown:

  1. If the declared type contains the string "INT" then it is assigned INTEGER affinity.

  2. If the declared type of the column contains any of the strings "CHAR", "CLOB", or "TEXT" then that column has TEXT affinity. Notice that the type VARCHAR contains the string "CHAR" and is thus assigned TEXT affinity.

  3. If the declared type for a column contains the string "BLOB" or if no type is specified then the column has affinity BLOB.

  4. If the declared type for a column contains any of the strings "REAL", "FLOA", or "DOUB" then the column has REAL affinity.

  5. Otherwise, the affinity is NUMERIC.

Based on this, it looks like sqlite is interpreting your mystery_type datatype as NUMERIC.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.