A database from Ruby
A database keeps data in tables – rows and columns, like a spreadsheet – and answers questions about it in SQL. Sequel, by Jeremy Evans (who also wrote Roda from lesson 55), lets you do all of that in Ruby: you call methods, and Sequel writes the SQL.
Underneath runs SQLite, the small database that lives in every phone and browser. Here it runs right in this page (about 1 MB, loaded when you open the lesson) and keeps the database in memory – a reload starts empty. Let's build a little time tracker:
install_gem "sequel"
require "sequel"
DB = Sequel.sqlite # a database in memory
DB.create_table(:entries) do
primary_key :id
String :project, null: false
Float :hours
Date :day
TrueClass :billable, default: false
end
DB.tablesSequel.sqlite opens a database; DB is the usual name for it. create_table describes a table: primary_key :id numbers the rows by itself, and each line after it is a column with its type – text, a decimal number, a date, true or false. null: false means the project may never be empty.
Now some rows. DB[:entries] is the table as a dataset, and insert adds a row:
entries = DB[:entries]
entries.insert(project: "Chunky", hours: 2.5, day: Date.new(2026, 10, 5), billable: true)
entries.insert(project: "Bacon", hours: 1.0, day: Date.new(2026, 10, 5))
entries.insert(project: "Chunky", hours: 3.0, day: Date.new(2026, 10, 6), billable: true)
entries.insert(project: "Speck", hours: 0.5, day: Date.new(2026, 10, 6))
entries.countEach insert takes a hash, column by column; what you leave out (billable on the Bacon row) gets its default. Reading back works like an array of hashes:
entries.order(:day).each do |row|
puts "#{row[:day]} #{row[:project].ljust(7)} #{row[:hours]} h #{row[:billable] ? "$" : ""}"
end
row = entries.first
[row.class, row[:day].class, row[:billable].class]Every row is a plain Ruby hash, and the values have their Ruby types again: the day is a Date, billable is true or false – even though SQLite itself only knows numbers and text.
The real power is asking questions. A dataset method returns a new, narrower dataset, so you chain them like Ruby methods. sql shows what Sequel will send:
chunky = entries.where(project: "Chunky").order(:day)
puts chunky.sql
chunky.map(:hours)where(project: "Chunky") became WHERE (`project` = 'Chunky'), order became ORDER BY. Nothing is asked until you want the rows – here with map(:hours), which takes one column.
For comparisons, where takes a block in which column names are just names. And SQL can count and add up for you:
puts entries.where { hours > 2 }.count
puts entries.sum(:hours)
entries.group_and_count(:project).order(:project).allTwo entries have more than 2 hours; 7.0 hours in total; group_and_count counts the rows of each project. Now the question every time tracker exists for – how many hours per project? group puts the rows of a project together, and sum adds up each group:
timesheet = entries.group(:project).select(:project) { sum(:hours).as(:total) }.order(:project)
puts timesheet.sql
timesheet.allThat is a whole timesheet in one SQL query: the database does the adding, and Ruby gets three short rows. With many thousands of entries, that is much faster than loading them all into Ruby.
Changing and removing rows works on a dataset too – on all of its rows at once:
entries.where(project: "Bacon").update(billable: true)
entries.where(project: "Speck").delete
entries.where(billable: true).map(:project)update changed every Bacon row, delete removed every Speck row. Careful: DB[:entries].delete without a where empties the whole table.
For a real program, Sequel has models: a class per table, an object per row, with your own methods on it:
class Entry < Sequel::Model(:entries)
def summary
"#{day}: #{hours} h for #{project}"
end
end
Entry.create(project: "Speck", hours: 1.5, day: Date.new(2026, 10, 7))
Entry.order(:day).map(&:summary)Sequel::Model(:entries) reads the table's columns and gives the class a method for each, so day, hours and project just work inside summary. create inserts a row and returns it as an object.
One more thing: the database guards its rules itself. The project column was declared null: false – let's try to break it:
begin
entries.insert(hours: 1.0) # no project
rescue Sequel::NotNullConstraintViolation => error
puts "Refused: #{error.class}"
end
entries.countSQLite refused the row, and Sequel turned the refusal into a Ruby exception you can rescue. The table still has its four rows.
So far the database has lived in memory: reload the page and it is gone. Give Sequel.sqlite a file name, and the database is a real SQLite file. create_table? – with a question mark – creates the table only if it is not there yet, so the cell can run again and again. Run it a few times:
timelog = Sequel.sqlite("timelog.db") # a database in a file
timelog.create_table?(:entries) do
primary_key :id
String :project, null: false
Float :hours
end
timelog[:entries].insert(project: "Chunky", hours: 1.5)
timelog[:entries].countEvery run adds a row, and the count grows: the rows are kept in timelog.db, not in the cell. Below the output the file is offered as a download – a real SQLite database that opens in any SQLite tool, such as DB Browser for SQLite. In a lesson the file lasts as long as the page is open; in the workshop a program's database is kept with the project, and an uploaded .db file opens the same way.
gem install sequel sqlite3. The code runs unchanged, and timelog.db is a file next to your program. Sequel also talks to PostgreSQL and MySQL with the same Ruby code. Here in the browser the sqlite3 gem – a C extension – is replaced by a small stand-in on sql.js, SQLite compiled to WebAssembly; Sequel itself is the real gem. Sequel and sql.js come under the MIT licence; SQLite is in the public domain.
hours_per_project as a Ruby hash, such as {"Bacon" => 1.5, …}.install_gem "sequel"
require "sequel"
log = Sequel.sqlite
log.create_table(:work) do
primary_key :id
String :project
Float :hours
end
log[:work].import([:project, :hours],
[["Chunky", 2.5], ["Speck", 0.5], ["Bacon", 1.5], ["Chunky", 3.0], ["Speck", 1.5]])
# hours_per_project = ... (a Ruby hash: project => hours)