Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should one use data type REAL versus NUMERIC in sqlite?

Tags:

sqlite

In sqlite, REAL and NUMERIC data types seem similar. Since NUMERIC supports Decimal(10,5), when should one use REAL instead?

https://www.tutorialspoint.com/sqlite/sqlite_data_types.htm

I am using sqlite3.

like image 908
guagay_wk Avatar asked Sep 13 '18 09:09

guagay_wk


People also ask

What is real data type in SQLite?

SQLite provides five primary data types which are mentioned below – NULL – It is a NULL value. INTEGER – It is an integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the value. REAL – It is a floating point value, stored as an 8-byte floating number.

What is the difference between integer and numeric in SQLite?

A column that uses INTEGER affinity behaves the same as a column with NUMERIC affinity. The difference between INTEGER and NUMERIC affinity is only evident in a CAST expression: The expression "CAST(4.0 AS INT)" returns an integer 4, whereas "CAST(4.0 AS NUMERIC)" leaves the value as a floating-point 4.0.

What is numeric data type in SQLite?

All "values" in SQLite3 (that is, at the intersection of any row and column) may contain data of any of the following datatypes: INTEGER , a 64-bit signed integer. REAL , a 64-bit IEEE-754 floating point number. TEXT , a bag-o-bytes that conforms to C String semantics containing UTF-8 or UTF-16 encoded data.


1 Answers

SQLite, unlike most other RDBMS, uses a dynamic type system. This means that any of SQLite's five storage classes can be present in any column, despite that the column belongs to one type. But obviously, it is not best practice to mix types within a single column. For example, mixing numeric and character data in the same column is bad practice, as it would be in any database. The five actual storage classes in SQLite are:

  • NULL
  • INTEGER
  • REAL
  • TEXT
  • BLOB

The REAL storage class is used for numeric data with a decimal component. Floats would fit into this category. Other numbers without a decimal component would be assigned to the INTEGER storage class.

SQLite introduced a concept known as type "affinities." They were introduced in order to maximize compatibility between SQLite and other databases. From the documentation, we can see that the NUMERIC affinity is associated with the following types:

  • NUMERIC
  • DECIMAL(10,5)
  • BOOLEAN
  • DATE
  • DATETIME

So, if you are intending to store exact DECIMAL(10,5) data, then a NUMERIC affinity would make sense. On the other hand, the affinity REAL is associated with floating point (not exact) decimal data. Again, you may store either type in either column, but from a compatibility point of view, you may follow the affinity rules.

like image 130
Tim Biegeleisen Avatar answered Sep 20 '22 17:09

Tim Biegeleisen