Tcl SQLite
last modified November 24, 2026 Tcl 8.6
SQLite is an embedded database: a library that stores a whole relational
database in one file, with no server process and no configuration. The Tcl
binding turns a database file into a command, so SQL is executed by calling that
command. sqlite3 db library.db creates a command named
db, and from then on db eval runs SQL against the file
library.db.
This article installs the binding, creates a small books database, and works through inserts, queries, parameters, updates and a report. It ends with a Tk table that reads the same file. The examples share one database, so run them in order. The format page explains the column formatting used in the report.
Installing the sqlite3 Tcl package
The binding is a separate package, not part of the core interpreter. On Debian
and Ubuntu it comes from libsqlite3-tcl:
sudo apt install libsqlite3-tcl. Nothing else is needed; the
package contains the shared library and a pkgIndex.tcl that lets
Tcl find it.
Until the package is installed, package require sqlite3 fails with
can't find package sqlite3. That message means the binding is
missing, not that SQLite itself is missing, because the sqlite3
shell program is usually installed already. After the installation the same
command returns a version number, and every example below can run.
Opening a database
sqlite3 takes the name of an existing command, the path of the
database file, and optional options. If the file does not exist, SQLite creates
it as an empty file that grows when the first table is written. The new command
is created in the global namespace and is removed with db close,
which also commits pending work and releases the file lock.
package require sqlite3
set file library.db
sqlite3 db $file
puts "opened $file"
puts "sqlite version: [db version]"
puts "tables: [db eval {SELECT count(*) FROM sqlite_master}]"
db close
The script stores the file name in a variable first so that the same name can be
printed. db version reports the version of the SQLite library
linked into the Tcl package, and sqlite_master is the catalog table
that lists every object in the database, so counting its rows tells whether the
file already has tables.
$ tclsh open_db.tcl opened library.db sqlite version: 3.37.2 tables: 0
Creating a table
SQL statements are passed to db eval inside braces. Braces stop Tcl
substitution, which is what SQL wants: the text reaches SQLite unchanged. The
table below has an integer primary key, two required text columns and a year.
IF NOT EXISTS makes the script safe to run twice.
package require sqlite3
sqlite3 db library.db
db eval {
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER
)
}
puts "table books is ready"
puts "tables: [db eval {SELECT name FROM sqlite_master WHERE type = 'table'}]"
db close
SQLite creates the id value automatically when it is left out of an
insert, and NOT NULL rejects a row without a title or an author. The
last line queries sqlite_master for table names, which is a quick
way to confirm that the statement took effect. db eval returns the
first column of every result row as a list when no script is given.
$ tclsh create_table.tcl table books is ready tables: books
Inserting rows
An insert names the columns and supplies the values. Text values are quoted with
single quotes, which is the SQL convention, while numbers are written as they
are. Each call to db eval is its own transaction, so the three rows
below are committed one by one.
package require sqlite3
sqlite3 db library.db
db eval {INSERT INTO books (title, author, year)
VALUES ('The C Programming Language', 'Kernighan and Ritchie', 1978)}
db eval {INSERT INTO books (title, author, year)
VALUES ('The Practice of Programming', 'Kernighan and Pike', 1999)}
db eval {INSERT INTO books (title, author, year)
VALUES ('Tcl and the Tk Toolkit', 'Ousterhout', 1994)}
puts "rows: [db onecolumn {SELECT count(*) FROM books}]"
db close
db onecolumn is a shortcut for a query that returns exactly one
value; it is used here to print the row count. The identifiers 1, 2 and 3 were
assigned in insertion order, but nothing guarantees that an id stays next to a
particular title once rows are deleted. Order reports by a column such as
year, not by id, unless the order of insertion is
really what you mean.
$ tclsh insert_rows.tcl rows: 3
Querying with db eval
When db eval receives a script as its last argument, it runs that
script once per result row. Every column of the current row is available as a
Tcl variable with the column name. This is the most convenient way to process a
result set, because no separate fetch loop and no explicit statement handle are
needed.
package require sqlite3
sqlite3 db library.db
db eval {SELECT id, title, year FROM books ORDER BY year} {
puts [format "%2d %-32s %4d" $id $title $year]
}
puts "---"
set titles [db eval {SELECT title FROM books WHERE year > 1990 ORDER BY title}]
puts "after 1990: $titles"
db close
Inside the braces, $id, $title and $year
are the columns of the current row, not variables from the surrounding scope.
The query orders by year, which is why the ids appear as 1, 3, 2. Without a
script, db eval collects the first column of every row into a list,
so the second query returns the matching titles in one value.
$ tclsh query_books.tcl
1 The C Programming Language 1978
3 Tcl and the Tk Toolkit 1994
2 The Practice of Programming 1999
---
after 1990: {Tcl and the Tk Toolkit} {The Practice of Programming}
Prepared statements and parameters
Building SQL by gluing strings together breaks as soon as a title contains a
quote, and it invites SQL injection. Parameters solve both problems.
db eval compiles the statement once, and a name such as
:title in the SQL is bound to the Tcl variable of the same name.
The compiled statement is cached by the binding, so a loop that runs the same
SQL reuses it.
package require sqlite3
sqlite3 db library.db
set newBooks {
{{The Art of Unix Programming} Raymond 2003}
{{Code Complete} McConnell 2004}
}
db transaction {
foreach book $newBooks {
lassign $book title author year
db eval {
INSERT INTO books (title, author, year)
VALUES (:title, :author, :year)
}
}
}
set since 2000
puts "books since $since:"
db eval {SELECT title, author FROM books WHERE year >= :since
ORDER BY year} row {
puts " $row(title) by $row(author)"
}
db close
The book records are three-element lists, and lassign unpacks each
one into title, author and year; the
names then match the parameters in the SQL. db transaction wraps
the loop in BEGIN and COMMIT, so either all rows are
stored or none are, and the commit is much faster than one transaction per
insert.
The second query shows the array form. db eval SQL row { ... } runs
the script once per row and stores the current row in the array named
row, so the body can read $row(title) and
$row(author); the element row(*) holds the column
names. The :since parameter is still bound from the Tcl variable of
the same name.
$ tclsh params.tcl books since 2000: The Art of Unix Programming by Raymond Code Complete by McConnell
Updating and deleting
UPDATE and DELETE use the same db eval
call as the other statements. db changes reports how many rows the
last statement modified, which is useful in a report or in a test. Running the
two statements below on the shared file turns the 1978 book into a 1988 book and
then removes it.
package require sqlite3
sqlite3 db library.db
db eval {UPDATE books SET year = 1988
WHERE title = 'The C Programming Language'}
puts "updated: [db changes]"
db eval {DELETE FROM books WHERE year < 1990}
puts "deleted: [db changes]"
db eval {SELECT year, title FROM books ORDER BY year} {
puts "$year $title"
}
db close
The update statement matches by title and changes only the year. The delete
statement matches a range and removes one row. Both counts are printed
immediately after the statement, because db changes refers to the
most recent one. Without a WHERE clause the same statements would
touch every row in the table, which is rarely intended.
$ tclsh update_delete.tcl updated: 1 deleted: 1 1994 Tcl and the Tk Toolkit 1999 The Practice of Programming 2003 The Art of Unix Programming 2004 Code Complete
A small report
A report is a query plus formatting. format aligns the columns,
string repeat draws the rule under the header, and a second query
with GROUP BY produces the summary. The query uses integer division
to turn a year into a decade, which keeps the grouping expression in SQL.
package require sqlite3
sqlite3 db library.db
puts [format "%-34s %4s" "TITLE" "YEAR"]
puts [string repeat "-" 39]
db eval {SELECT title, year FROM books ORDER BY year} {
puts [format "%-34s %4d" $title $year]
}
puts ""
puts "books per decade:"
db eval {SELECT (year / 10) * 10 AS decade, count(*) AS total
FROM books GROUP BY decade ORDER BY decade} {
puts [format " %d: %d" $decade $total]
}
puts "total: [db onecolumn {SELECT count(*) FROM books}]"
db close
The first query returns four rows after the update and the delete. The second
groups them by decade and counts the rows in each group; the alias
decade becomes the name of the column variable inside the script.
The final onecolumn query prints the total, so the report has a
header, a body and a footer, the shape most printed reports need.
$ tclsh report.tcl TITLE YEAR --------------------------------------- Tcl and the Tk Toolkit 1994 The Practice of Programming 1999 The Art of Unix Programming 2003 Code Complete 2004 books per decade: 1990: 2 2000: 2 total: 4
Showing a table in Tk
The same query drives a graphical table. ttk::treeview displays
rows and columns, and each result row becomes one item with the title as its
text and the remaining fields as values. This is a sketch of the idea rather
than a complete application: there is no scrolling, no editing and no
refresh button.
package require Tk
package require sqlite3
sqlite3 db library.db
wm title . "Books"
ttk::treeview .tree -columns {author year} -height 6
.tree heading #0 -text Title
.tree heading author -text Author
.tree heading year -text Year
.tree column #0 -width 260
.tree column author -width 150
.tree column year -width 60 -anchor e
db eval {SELECT title, author, year FROM books ORDER BY year} {
.tree insert {} end -text $title -values [list $author $year]
}
pack .tree -fill both -expand 1
after 500 {
puts "rows in tree: [llength [.tree children {}]]"
db close
destroy .
}
The script loads both Tk and the SQLite package. The tree gets two data columns
in addition to the implicit tree column, and the headings and widths are set
before the rows are inserted. db eval runs its script once per row,
and .tree insert appends an item at the end of the top level. Run
the file with wish, not tclsh, because
package require Tk needs a display.
$ wish tk_table.tcl rows in tree: 4
Source
The SQLite project documents the Tcl interface and the SQL dialect, while the
Tcl manual covers format and the list commands used above. The Tk
treeview is described in the Tk manual.
This article installed the SQLite binding for Tcl and used it to create a database, define a table, insert and query rows, bind parameters, update and delete data, and print a report. The database file stays a plain file that other programs can open. The Tcl dictionary page is a good next step, because a result row can always be turned into a dictionary when a script needs to pass it around.
Author
List all Tcl Tutorials.