top | item 34584493

(no title)

mytherin | 3 years ago

Most implementations of SQL are not dynamically typed - they are statically typed. There is an explicit compilation phase (`PREPARE`) that compiles the entire plan and handles any type errors.

For example - this query throws a type error when run in Postgres during query compilation without executing anything or reading a row of the input data:

   CREATE TABLE varchars(v VARCHAR);
   PREPARE v1 AS SELECT v + 42 FROM varchars;

   ERROR:  operator does not exist: character varying + integer
   LINE 1: PREPARE v1 AS SELECT v + 42 FROM varchars;
                               ^
   HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

The one notable exception to this is SQLite which has per-value typing, rather than per-column typing. As such SQLite is dynamically typed.

discuss

order

randomdata|3 years ago

That is strong typing. Python, a dynamically typed language, exhibits the same quality:

    >>> v = ""
    >>> v + 42
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can only concatenate str (not "int") to str
Types are most certainly not static (at least not in Postgres or most other implementations):

    CREATE TABLE varchars(v VARCHAR);
    ALTER TABLE varchars ALTER COLUMN v TYPE INTEGER USING v::integer;
    PREPARE v1 AS SELECT v + 42 FROM varchars;

mytherin|3 years ago

Types are static within the context of a query, not necessarily within the context of the lifetime of a database. Types are determined and propagated at query compile time. In a query, the value "v" refers to a VARCHAR column (as determined by the table definitions). At query compile time an error is thrown when a type violation is detected.

It is distinct from Python because in Python individual objects have types - and type resolution is done strictly at run-time. There is no compile time type checking because types do not exist at compile time at all. Note how in my example I am preparing (i.e. compiling) a query, whereas in your example you are executing the statement.

If you refrain from changing the types of columns in a database and prepare your queries you can detect all type errors before having to process a single row. That is not possible in a dynamically typed language like Python, and is very comparable to the guarantees that a language like Typescript offers you.