SQLite command-line queries

SQLite provides a nice command-line interface for managing databases, but what if we need to run queries from a script? If you have been trying to call SQLite from a Bash script with the “-init” argument, in quest of running SQL queries from a file to the database, you would have also found out that SQLite stays in interactive mode, forcing you to watch the console and exit each time. This becomes a problem once we have many (potentially large) query files that have to be run one after the other, such as when we need to build and rebuild a test database.

So if you are here, your script probably contains something like this:

sqlite3 -init query1.sql mydatabase.db
sqlite3 -init query2.sql mydatabase.db
sqlite3 -init query3.sql mydatabase.db

And each individual command would leave you in interactive mode, forcing you to close it each time with “.exit” for the script to resume its work.

SQLite also allows us to use the input redirection operator to direct file content (or a query directly written in single-quotes) as input. Like this:

sqlite3 mydatabase.db < query1.sql
sqlite3 mydatabase.db < query2.sql
sqlite3 mydatabase.db < query3.sql

This will redirect the content of each file directly into the database without any need for manual intervention.

If you need more information on using SQLite in command-line, then visit their official documentation at https://sqlite.org/cli.html.

Leave a Reply