create-table --sql option for CREATE TABLE AS SELECT

Refs #481
This commit is contained in:
Chris (ChrisJr404) 2026-08-18 19:02:35 -04:00
commit a6dfd7a7af
No known key found for this signature in database
4 changed files with 171 additions and 2 deletions

View file

@ -952,7 +952,7 @@ See :ref:`cli_create_table`.
::
Usage: sqlite-utils create-table [OPTIONS] PATH TABLE COLUMNS...
Usage: sqlite-utils create-table [OPTIONS] PATH TABLE [COLUMNS]...
Add a table with the specified columns. Columns should be specified using
name, type pairs, for example:
@ -965,7 +965,13 @@ See :ref:`cli_create_table`.
Valid column types are text, integer, real, float, blob and any.
Use --sql to create the table from the results of a SQL query instead:
sqlite-utils create-table my.db tall_people \
--sql "select * from people where height > 180"
Options:
--sql TEXT Create the table using the results of this SQL query
--pk TEXT Column to use as primary key
--not-null TEXT Columns that should be created as NOT NULL
--default <TEXT TEXT>... Default value that should be set for a column

View file

@ -2167,6 +2167,15 @@ Use the ``any`` type for a strict column that should accept integers, floating p
"name" TEXT
) STRICT
Instead of listing columns you can populate a new table from the results of a SQL query using ``--sql``. This is a shortcut for ``CREATE TABLE name AS ...``:
.. code-block:: bash
sqlite-utils create-table mydb.db tall_people \
--sql "select * from people where height > 180"
The new table takes its columns from the query, so ``--sql`` cannot be combined with column definitions or with the ``--pk``, ``--not-null``, ``--default``, ``--fk``, ``--transform`` and ``--strict`` options. It does work with ``--ignore`` and ``--replace``.
If a table with the same name already exists, you will get an error. You can choose to silently ignore this error with ``--ignore``, or you can replace the existing table with a new, empty table using ``--replace``.
You can also pass ``--transform`` to transform the existing table to match the new schema. See :ref:`python_api_explicit_create` in the Python library documentation for details of how this option works.