sqlx-cli - Database and Migration Command Line Tool
Learn how to install and use sqlx-cli to create databases, manage migrations, and interact with your SQLx database from the command line
sqlx-cli - Database and Migration Command Line Tool
This page covers sqlx-cli, a command-line tool that helps you manage databases and schema changes when building Rust applications with the SQLx library. SQLx itself is a Rust crate for talking to SQL databases directly from your code. sqlx-cli is a separate program you install on your machine that works alongside SQLx to handle database setup and versioned migrations.
You will learn what sqlx-cli is, why it exists, how to install it with support for different database engines, and how to use its main commands in real projects. By the end of this page, you will be able to create a database from the terminal, generate a new migration file, apply those migrations, and revert reversible (-r) migrations when needed.
What Exactly Is sqlx-cli
Think of sqlx-cli as a helper program that sits outside your Rust code. While your Rust application uses the SQLx library to read and write data at runtime, sqlx-cli handles the setup and schema changes that happen before your application starts or during development. It gives you a set of terminal commands instead of making you write custom scripts or manually connect to your database with a GUI client.
The tool's main jobs are:
- Creating and deleting databases for development
- Generating timestamped migration files
- Applying migrations in the correct order
- Reverting migrations one at a time
- Showing the current migration status
A migration is a small SQL file that describes one change to your database schema, like creating a table, adding a column, or fixing an index. Migrations let you version your database structure just like you version your code with Git. sqlx-cli reads a migrations folder in your project and runs those files against a database in the correct sequence.
sqlx-cli vs sqlx library:
The sqlx crate you add to Cargo.toml is a library used inside your Rust application. sqlx-cli is a standalone executable you install globally with Cargo. Both are part of the same SQLx project, but you use them at different times. This page covers only the command-line tool.
Why You Need a Command Line Tool for Databases
You can create a database and tables using a graphical tool like DBeaver or psql directly. That works fine for a quick experiment, but it becomes messy when you work on a team or need to reproduce the same database on another machine. If Alice creates a table manually and Bob creates a slightly different table manually, the two local databases slowly drift apart. When the application behaves differently for each developer, debugging becomes painful.
Migrations solve that problem by storing every schema change as a file in version control. Everyone on the team runs the same migration files, so every database ends up with the same structure. sqlx-cli is the tool that reads those files and applies them in a reliable, ordered way. You write the SQL once, commit it, and anyone can reproduce your exact database state with a single command.
Another advantage is speed. During active development you often need to wipe a database and start fresh. sqlx database reset can drop and recreate a database with all migrations applied in one step. Without a tool like this, you would have to write your own shell scripts that call psql or mysql directly, which is repetitive and error-prone.
Installing sqlx-cli with Cargo
Because sqlx-cli is published on crates.io, the Rust package registry, the standard way to install it is with cargo install. This command downloads the source code, compiles it, and places the finished executable into your Cargo bin directory, which is usually already on your PATH.
The exact command depends on which database engine you plan to use. SQLx supports PostgreSQL, MySQL, and SQLite, but you only compile in the features for the databases you actually need. This keeps the binary smaller and avoids pulling unnecessary dependencies.
PostgreSQL is the most common choice for Axum backends. Install sqlx-cli with the postgres feature enabled:
cargo install sqlx-cli --no-default-features --features postgres
The --no-default-features flag disables the default set of features (which includes all database types), and --features postgres enables only the PostgreSQL support. This gives you a leaner binary that compiles faster.
If you only ever work with one database engine, the minimal feature command is the right choice. If you want a universal binary that can talk to any supported database, you can omit --no-default-features and simply run:
cargo install sqlx-cli
That compiles a larger tool that includes support for PostgreSQL, MySQL, and SQLite. It takes longer to build and uses more disk space, but it is convenient if you switch between projects with different databases.
Compile time can be long:
Installing sqlx-cli from source compiles many dependencies. On a typical machine this can take several minutes. That is normal. The binary is cached afterwards, so you only pay this cost once.
After installation completes, verify that the sqlx command is available:
sqlx --version
You should see output similar to:
sqlx-cli 0.9.0
If you see "command not found", make sure your Cargo bin directory is on your PATH. On Linux and macOS that is usually ~/.cargo/bin, and on Windows it is %USERPROFILE%\.cargo\bin.
Where sqlx-cli Looks for Database Connection Information
Before running most sqlx commands, the tool needs to know how to connect to your database. It looks for a DATABASE_URL environment variable. You can set it inline before a command:
export DATABASE_URL=postgres://postgres:password@localhost:5432/mydb
sqlx database create
But typing that every time is tedious. A much better approach is to create a .env file in your project's root directory. sqlx-cli automatically reads that file and uses the variables inside it.
Create a file named .env with content like this:
DATABASE_URL=postgres://postgres:password@localhost:5432/mydb
The format is postgres://USER:PASSWORD@HOST:PORT/DATABASE_NAME. Replace USER, PASSWORD, HOST, PORT, and DATABASE_NAME with your actual values. On a typical local install, your superuser is likely postgres and the port is 5432.
Never commit the .env file:
The .env file contains your database password in plain text. Add it to .gitignore immediately. If you accidentally commit it, anyone who clones your repository will have your credentials. This is a common and serious security mistake.
Once the .env file exists in the current working directory (or any parent directory), sqlx-cli will find it automatically. You can confirm it is being read by running a command that requires a database connection and watching the output for the correct database name.
A First End-to-End Workflow
The following steps take you from a fresh project folder to a database with a table, using only sqlx-cli and a text editor. This is the exact workflow you will repeat many times during development.
Step 1: Create a .env file
In your project root, create a file named .env with your database URL:
DATABASE_URL=postgres://postgres:password@localhost:5432/axum_app
Make sure the database axum_app does not already exist; we will create it in the next step.
Step 2: Create the database
Run the create command:
sqlx database create
The command prints nothing on success. If the database already exists, it simply succeeds and leaves the existing database untouched.
Step 3: Generate a migration file
Create a migration for a new users table:
sqlx migrate add create_users_table
This creates a new folder named migrations in your current directory if it does not already exist, and inside it a timestamped SQL file like 20250314120000_create_users_table.sql.
Step 4: Write the migration SQL
Open the newly created .sql file in your editor. It will be empty. Replace its content with:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE
);
This SQL creates a table named users with three columns: an auto-incrementing integer primary key, a unique text column for the username, and a unique text column for the email.
Step 5: Apply the migration
Run:
sqlx migrate run
The tool connects to the database, looks at the migrations folder, and applies any migrations that have not yet been run. Output:
Applied 20250314120000/migrate create users table (1.234ms)
The exact time may differ, but the important part is that the migration was applied.
Your database is ready:
If you saw "Applied" followed by the migration name, everything worked. You now have a database with a users table that matches the SQL you wrote. You can verify this by connecting to the database with any PostgreSQL client and running \dt or SELECT * FROM users;.
Understanding Migration Files and Folder Structure
When you run sqlx migrate add <name>, the tool creates a migrations folder (if it does not exist) and inside it a file with a specific naming pattern:
20250314120000_create_users_table.sql
With sqlx migrate add -r <name>, you get a pair instead: ….up.sql and ….down.sql. The revert section further down explains how the pair is used.
The first part is a UTC timestamp with the format YYYYMMDDHHMMSS. The timestamp ensures that migrations are sorted chronologically. The rest is the name you provided, with spaces replaced by underscores. The order of migration execution is determined by the timestamp, not by the filename's alphabetical order.
A typical migrations folder after a few changes might look like:
migrations/
├── 20250314120000_create_users_table.sql
├── 20250315100000_add_age_column_to_users.sql
├── 20250315150000_create_posts_table.up.sql
└── 20250315150000_create_posts_table.down.sql
Each up file (or single .sql file) contains one or more SQL statements. sqlx migrate run reads these files in timestamp order and applies the ones it has not yet seen. It tracks which migrations have already been applied in a special table inside your database named _sqlx_migrations. You do not need to create this table manually; sqlx-cli handles it automatically the first time you run a migration.
The sqlxmigrations table:
Do not edit or delete the _sqlx_migrations table. It is the database's record of which migration files have been applied. If you delete it, sqlx migrate run will try to run all migrations again, which will fail because the tables already exist.
Reverting a Migration
Sometimes you realize a migration was wrong. Perhaps you added a column with the wrong type, or you created a table that should not exist. Instead of manually dropping tables, you can use sqlx migrate revert to undo the most recently applied migration.
sqlx migrate revert only works when the migration was created as a reversible pair. Create that with the -r / --reversible flag:
sqlx migrate add -r create_posts_table
That creates two files instead of one:
migrations/
20250315150000_create_posts_table.up.sql
20250315150000_create_posts_table.down.sql
Put the forward change in the .up.sql file and the undo SQL in the matching .down.sql file:
-- 20250315150000_create_posts_table.up.sql
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
body TEXT NOT NULL
);
-- 20250315150000_create_posts_table.down.sql
DROP TABLE posts;
A plain sqlx migrate add create_posts_table (without -r) creates a single .sql file. That file is for applying only. There is no special -- Add migration script here marker that splits up and down in one file - that old pattern is outdated. Without a .down.sql companion, sqlx migrate revert cannot undo schema changes for that migration.
Apply, then revert:
sqlx migrate run
sqlx migrate revert
Example output:
Applied 20250315150000/migrate create posts table (0.9ms)
Applied 20250315150000/revert create posts table (0.7ms)
The posts table is gone from your database, but the migration files still exist in your migrations folder. This is useful when you want to change the SQL and reapply.
Use -r when you need revert:
If you need sqlx migrate revert, create migrations with sqlx migrate add -r <name> and keep the .down.sql accurate. For a non-reversible single .sql migration, revert will not undo the schema; write a new forward migration instead, or reset the database in local development with sqlx database reset.
Checking Migration Status
Before applying or reverting, it is helpful to see which migrations have already been applied. Run:
sqlx migrate info
This prints one line per migration, with the version (timestamp), whether it is applied, and its description. A sample output:
20250314120000/installed create users table
20250315100000/installed add age column to users
20250315150000/pending create posts table
The word after the slash tells you the state. installed means the migration has been applied to your local database; pending means it exists as a file but has not been run yet. This command is read-only and does not modify anything.
Creating and Dropping Databases
The sqlx database create command creates a new database using the connection URL. It extracts the database name from the URL and sends a CREATE DATABASE statement to the server. The command prints nothing on success, and it is idempotent: if the database already exists, it simply succeeds and leaves the existing database untouched.
sqlx database create
Similarly, sqlx database drop deletes the database completely, including all tables and data:
sqlx database drop
The command prints nothing on success. Before dropping, it asks for confirmation:
Drop database at postgres://postgres:password@localhost:5432/axum_app? [y/N]
The default answer is No, so pressing Enter keeps the database. Pass -y to skip the prompt (sqlx database drop -y).
Because this is destructive, always double-check which database you are pointing at before running it. A common mistake is having the wrong DATABASE_URL and dropping a production database instead of a local one.
Drop is permanent:
sqlx database drop asks for confirmation, but once you confirm, all data in that database is gone forever. Always ensure your DATABASE_URL points to a local development database, never a production or shared environment. Consider creating a backup or export before dropping.
Using sqlx database reset for a Fresh Start
During development, you often want to wipe everything and re-run all migrations from scratch. The sqlx database reset command combines drop and create and then runs all pending migrations:
sqlx database reset
This is extremely convenient when you have made changes to your migration files and want to test them from a clean state. The tool drops the database if it exists, recreates it, and applies every migration in order. Like drop, it asks for confirmation first (pass -y to skip the prompt).
Output might look like:
Drop database at postgres://postgres:password@localhost:5432/axum_app? [y/N]
Applied 20250314120000/migrate create users table (1.1ms)
Applied 20250315100000/migrate add age column to users (0.8ms)
After this command, your database contains exactly what your migration files define, nothing more.
Working with the .env File in Practice
Your .env file can contain more than just DATABASE_URL. You can store any environment variables your application or tooling needs. For sqlx-cli specifically, the DATABASE_URL is the only one it reads directly, but having other variables like DATABASE_MAX_CONNECTIONS is fine for your Rust application to read later.
A sample .env for a typical Axum project:
DATABASE_URL=postgres://postgres:secret@localhost:5432/axum_app
Always keep .env in your project root where you run the sqlx commands. If you run sqlx from a subdirectory, it will still search parent directories for the .env file, but it is simplest to run commands from the root.
You can override the .env file by setting an environment variable directly in the terminal before the command:
DATABASE_URL=postgres://postgres:otherpass@localhost:5432/other_db sqlx database create
Inline environment variables take precedence over .env file values. This can be useful for testing different environments without editing the file.
Common Workflows with sqlx-cli and Cargo Watch
Since you are working in an Axum project, you likely already use cargo-watch to auto-restart your server when code changes. You can combine that with sqlx-cli commands in your terminal. A common pattern is:
- Start your database server (e.g., Docker container with PostgreSQL).
- Run
sqlx database createonce to ensure the database exists. - Run
sqlx migrate runto apply the latest schema. - Start your application with
cargo watch -x run. - When you need to change the schema, create a new migration with
sqlx migrate add, edit the SQL, then stop your app, runsqlx migrate run, and restart the app.
You do not need to run sqlx migrate run every time you start your app. Once migrations are applied, they stay applied until you add new ones or reset the database.
Verifying Your sqlx-cli Setup with a Small Project
To confirm everything works together, create a temporary Rust project and simulate a migration workflow without writing any actual Rust code. This is purely to test the CLI and your database connection.
First, create a new folder and a .env file:
mkdir sqlx-cli-test
cd sqlx-cli-test
echo 'DATABASE_URL=postgres://postgres:password@localhost:5432/test_db' > .env
Then create the database:
sqlx database create
Generate a migration:
sqlx migrate add init
Open the generated file and add:
CREATE TABLE books (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL
);
Apply it:
sqlx migrate run
Check status:
sqlx migrate info
If all steps work, you have a fully functional sqlx-cli setup. You can delete this test folder afterwards; the database test_db will remain but you can drop it with:
sqlx database drop
Handling Multiple Database Engines
If you work on projects that use different databases, you can install sqlx-cli multiple times with different features, or install one binary with all features. The binary name is always sqlx, so you cannot have two versions easily. The recommended approach is to install the full-featured version once:
cargo install sqlx-cli
Then adjust the DATABASE_URL scheme accordingly. PostgreSQL URLs start with postgres://, MySQL with mysql://, and SQLite uses a file path like sqlite://data.db. The CLI will automatically use the correct database driver based on the URL.
For example, to create a SQLite database file named dev.db:
DATABASE_URL=sqlite://dev.db sqlx database create
Then add and run migrations against that file the same way. The same sqlx migrate run command works because the CLI detects SQLite from the URL.
Troubleshooting Common Beginner Mistakes
New users often hit a few predictable roadblocks. The list below names each mistake and how to fix it.
Missing DATABASE_URL:
If you run sqlx database create without a .env file or environment variable, you will see an error like error: \--database-url` or `DATABASE_URL` must be set. The solution is to create a .envfile with your connection URL or exportDATABASE_URL` in your shell before running the command.
Wrong database URL scheme:
Forgetting to use the correct URL prefix is common. If you use localhost:5432 without postgres://, the tool will not recognize the database type and may fail with a cryptic error. Always include the scheme, e.g., postgres://, mysql://, or sqlite://.
Migrations folder not found:
If you run sqlx migrate run before adding any migration, you will see an error like error: while resolving migrations: error canonicalizing path migrations. That is expected. Run sqlx migrate add <name> first to create the folder and an empty migration file.
Everything is working if you see the applied message:
After a successful sqlx migrate run, you should see output like Applied <timestamp>/migrate <description>. That is your confirmation that the database connection works, the migration folder is correct, and the SQL executed without errors. If you see that, you are set.
Another common issue is trying to run sqlx commands from a folder that is not inside your project. If your .env file is in the project root, but you opened a terminal in a subfolder like src, the tool may still find the .env by walking up parent directories, but it is safer to run commands from the project root.
Offline Mode and sqlx prepare (Brief Overview)
sqlx-cli has a feature called offline mode that lets you compile your Rust application without a live database connection. This is useful in CI environments where you cannot run a database server. The command sqlx prepare scans your Rust source code for SQL queries and writes them to a metadata file (.sqlx folder). Then, the SQLx library can validate queries at compile time without connecting to a database.
This is an advanced topic and not required for basic local development. For now, just know that the command exists and is part of sqlx-cli. You will likely encounter it later when setting up continuous integration or building for production. The core database and migration commands covered on this page are what you need right now.
Summary
The sqlx-cli tool is your command-line assistant for managing databases and schema migrations in Rust projects. You install it once with cargo install, choose the database features you need, and then use a small set of commands (database create, migrate add, migrate run, migrate revert, migrate info, database reset) to keep your database schema in sync with your code.
The most important mental model is that migrations are versioned SQL files. You write the change once, commit it to version control, and apply it everywhere with sqlx migrate run. This gives you reproducible databases across every developer machine and deployment environment.
As you continue building your Axum application, you will use sqlx-cli regularly during development. The next tools you might explore are API testing clients like HTTPie or Postman, which help you test the endpoints that eventually use the database you just set up. For now, you have a solid foundation in sqlx-cli that will carry you through every project that needs a database.