Org-mode and SQL
Literate programming with org-mode and sql.
Use literate programming to write and document SQL queries directly in Emacs.
While learning about Common Lisp and Emacs, I discovered this post about running a bakery using Emacs and org-mode1. The approach combines literate programming principles2—mixing natural language and code—with database work. This post explains how to set up Emacs for SQL development using org-mode and org-babel.
Follow these steps to be able to use SQL and org-mode:
- Configure org-mode in your emacs configuration file. Find my emacs configuration file here.
- Install and configure org-babel. Enable these languages:
;; Run/highlight code using babel in org-mode
(org-babel-do-load-languages
'org-babel-load-languages
'(
(lisp . t)
(shell . t)
(sql . t)
))
;; Syntax highlight in #+BEGIN_SRC blocks
(setq org-src-fontify-natively t)
;; Don't prompt before running code in org
(setq org-confirm-babel-evaluate nil)
- Configure database connection details in org-mode. You can set these per block, as shown in the documentation, or at the section level:
* Your section name
:PROPERTIES:
:header-args:sql: :engine postgresql :dbport 5432 :dbhost 127.0.0.1 :dbuser testuser :dbpassword password :database testdb
:END:
🡹
Footnotes
-
Org-mode is an Emacs extension for working with structured text. It supports literate programming through org-babel, spreadsheets, task management, and more. While powerful for these tasks, many users still prefer pen and paper for personal task management. ↩
-
Literate programming combines natural language and code snippets to express programs as a single document. This reference offers more detail. Donald Knuth originated the concept; modern implementations include Jupyter notebooks. ↩