#270: Persisting Data in DuckDB
Last week we made our first steps with DuckDB and its in-memory capabilities. In this post we persist data with DuckDB so that we can reuse it between our scripts.
Connect to a database
For this post we use a database connection. We can specify the database file to use our existing data, and should the file not already exist, DuckDB will create one for us.
When we use DuckDB in an application, we may go for the context manager to ensure that the connection is closed when we finished the data access:
Create tables by hand
As with all other database systems, we can create our tables by hand. Check the list of data types that we can use to find a fitting one.
When we run the code, DuckDB creates the test table, inserts a row and shows us the data in our new table:

Create tables for existing data
A much more common use case for an analytics database is that we already have the data, and we want to load it into the database. For that we can use the CREATE TABLE ... AS SELECT syntax and DuckDB will do its magic to assign the right data types for the columns:

Create indexes and constraints
While DuckDB creates indexes in the background, sometimes we want to have an explicit index. We can create an index with this command:
If we want to have a unique index, we can add the UNIQUE keyword to the command:
Inspect metadata
When we want to know what tables we have, we can query the duckdb_tables() function:

When we know what tables we have, we can use the DESCRIBE keyword to see some details about our table:

Drop tables
When we have a table that we no longer need, we can delete it with this command:
This will remove our table test.
Next
When we persist our data with DuckDB, we can reuse the data between our scripts and applications. The connection manager helps us to clean-up after us and makes sure that we do not run out of connections. Next week we take a deeper look at querying data in DuckDB.