sqldatabase-designtheorydatabase-engine

Why can't database engines use an auto column datatype?


When defining table in database, we set column types as int / varchar etc etc. Why can't it set to auto?

The database would recognize from the input and set the type itself, much like php handles variables. Also, youtube wouldn't have to crash their stats counter.


Solution

  • In some instances, you can (e.g. SQL Server's sql_variant or Oracle's ANYDATA).


    Whether that's a good idea is another matter...

    First of all, not having explicit schema (in the database), doesn't mean you can avoid implicit schema (implied by what your client application expects). For example, just because you have a string in the database, doesn't mean your application will be able to work with it, if it was originally implemented to expect a number. This is really an argument of dynamic vs. static typing, and static typing is generally acknowledged as superior for non-trivial programs.

    Furthermore, these "variant" types often have significant overhead and are problematic from the indexing and sargability perspective. For example, is 2 smaller than 10? Yes if these are numbers, no if they are strings!

    So if you know what you expect from the database (which you do in 99% cases), tell that to the database, so it can type-check and optimize it for you!