How do I run database queries directly from Vim using vim-dadbod?
Answer
:DB sqlite:mydb.sqlite SELECT * FROM users
Explanation
vim-dadbod by Tim Pope is a plugin that lets you interact with databases directly from Vim. It supports PostgreSQL, MySQL, SQLite, SQL Server, MongoDB, Redis, and many other database systems, all through a unified interface.
How it works
The :DB command takes a database URL and a SQL query. The URL follows a standard format: adapter:connection_string. vim-dadbod executes the query using the appropriate command-line client (like psql, mysql, or sqlite3) and displays the results in a new buffer.
You can set a default database connection with let g:db = 'postgresql://user:pass@localhost/mydb', then simply use :DB followed by your query without repeating the connection string. The plugin also works with visual selections: select a SQL statement in visual mode and run :'<,'>DB to execute just that portion.
The companion plugin vim-dadbod-ui adds a drawer-style interface with saved queries, table browsing, and connection management.
Example
Install the plugin and its UI companion:
Plug 'tpope/vim-dadbod'
Plug 'kristijanhusak/vim-dadbod-ui'
Plug 'kristijanhusak/vim-dadbod-completion'
let g:db = 'sqlite:myproject.db'
Common usage patterns:
" Run a query with explicit connection
:DB sqlite:mydb.sqlite SELECT * FROM users
" Use the default connection
:DB SELECT name, email FROM users WHERE active = 1
" Execute the current line as a query
:.DB
" Execute a visual selection
:'<,'>DB
" Open the database UI
:DBUI
With vim-dadbod-completion installed, you also get autocompletion for table names, column names, and SQL keywords when editing SQL files or dadbod buffers, making it a full database IDE inside Vim.