Sequel is the Ruby library (the "sequel" gem) that gives you a fluent, chainable API for talking to SQL databases. Using it means you install the gem, connect to a database with a connection string, and then build queries in Ruby instead of writing raw SQL strings by hand. It works with PostgreSQL, MySQL, MariaDB, SQLite, and several other databases through adapters. This guide walks through the whole cycle: installing, connecting, creating tables, inserting and reading data, and cleaning up. It assumes you have Ruby and Bundler installed and a database you are allowed to connect to.
What You'll Need
- Ruby installed (a recent stable version) and the
gemcommand available. - Bundler, if you want to manage dependencies in a project.
- A database server or file: SQLite needs no server, while PostgreSQL or MySQL need a running instance and credentials.
- The database adapter gem that matches your database, plus any native client libraries the adapter depends on.
- A terminal and a plain text editor or Ruby file to run your script.
Step-by-Step
- Install the gem. Run
gem install sequel. If you use Bundler, addgem "sequel"to your Gemfile and runbundle install. This installs the core library but not the database drivers. - Install the adapter for your database. Sequel loads a driver gem named after the adapter. For SQLite use
gem install sqlite3; for PostgreSQL usegem install pg; for MySQL usegem install mysql2. Without the driver, connecting raises an error about a missing adapter. - Open a connection. In a Ruby file, require Sequel and connect with a URL:
require "sequel"thenDB = Sequel.connect("sqlite://myapp.db"). For PostgreSQL the URL looks likepostgres://user:password@localhost/mydb. Keep the connection object in a constant or pass it around; do not reconnect for every query. - Check the connection. Call
DB.test_connection. It returns true when the database answers. If it raises, the URL, credentials, or driver is wrong. - Create a table. Use the schema DSL:
DB.create_table(:notes) do primary_key :id; String :title; String :body; DateTime :created_at; end. This runs a CREATE TABLE statement. Usecreate_table?if the table may already exist, or run migrations for anything you will keep. - Insert rows. Call
DB[:notes].insert(title: "First", body: "Hello", created_at: Time.now). The hash keys become column names. Insert returns the new primary key where the database supports it. - Read rows. Start with the dataset:
DB[:notes]. Add filters with.where(title: "First"), choose columns with.select(:id, :title), sort with.order(:created_at), and limit with.limit(10). Chain these freely; Sequel builds one SQL statement. Call.allto get an array of hashes, or.firstfor a single row. - Update and delete.
DB[:notes].where(id: 1).update(title: "Edited")changes matching rows.DB[:notes].where(id: 1).deleteremoves them. Always include awhereclause unless you truly mean every row. - Use transactions for multi-step changes. Wrap related writes in
DB.transaction do ... end. If an exception is raised inside the block, Sequel rolls the whole block back, so partial changes do not stick. - Inspect the SQL when unsure. Call
.sqlon a dataset to see the statement Sequel would run. This is the fastest way to confirm a filter or join is doing what you expect. - Close the connection. Call
DB.disconnectwhen your script finishes, especially in long-running or test processes, so connections are released back to the server.
Common Mistakes
The most frequent problem is forgetting the adapter gem: Sequel installs fine, then fails at connect time because pg, mysql2, or sqlite3 is missing. Another is calling .all on a dataset with no limit in a loop, which loads an entire table into memory; filter and limit first. People also write update or delete without where, changing every row. Mixing symbols and strings for column names inconsistently causes confusing errors, so pick one style. Finally, reconnecting inside a method called many times exhausts the connection pool; connect once and reuse the object.
Tips
Use .sql liberally while learning; it turns the fluent API into something you can check against the database. Prefer DB[:table] datasets over raw SQL strings for anything you will reuse, because they compose and are safer against quoting mistakes. Use Sequel.extension for optional features such as pagination or migration helpers rather than writing them yourself. In tests, point the connection at an in-memory SQLite database (sqlite://) so each run starts clean. Keep credentials out of source files; read connection URLs from environment variables. And when a query returns unexpected results, check the generated SQL before changing the Ruby code.
Troubleshooting
If you get "LoadError: cannot load such file" at connect time, the adapter gem is missing or built against the wrong Ruby; reinstall it. If authentication fails, re-check the username, password, host, and database name in the URL, and confirm the server is running and reachable. If a table is not found, verify the table name and that you connected to the intended database, since servers often host several. If inserts fail on a NOT NULL column, supply a value or give the column a default. If a transaction seems not to roll back, make sure the exception is actually raised inside the block and not rescued before it reaches Sequel. If results look stale, check for an open transaction that has not committed. If performance degrades, inspect the SQL for missing filters and confirm indexes exist on the columns you filter and join on.
Frequently Asked Questions
Is Sequel the same as ActiveRecord?
No. Both are Ruby database libraries, but Sequel is a lighter, dataset-oriented toolkit, while ActiveRecord is the ORM bundled with Rails and centered on model classes. Sequel can be used with or without models.
Do I need Rails to use Sequel?
No. Sequel is a standalone gem and works in plain Ruby scripts, Sinatra apps, and other frameworks.
Which databases does Sequel support?
It supports PostgreSQL, MySQL, MariaDB, SQLite, and several others through adapters. Each adapter needs its matching driver gem installed.
How do I see the SQL Sequel generates?
Call .sql on any dataset, for example DB[:notes].where(id: 1).sql. It returns the statement string without running it.
Can I use raw SQL with Sequel?
Yes. DB.fetch("SELECT ...") and DB.run("UPDATE ...") execute SQL directly, which is useful for statements the DSL does not cover.
What is a dataset?
A dataset is a lazy query object representing rows in a table. You chain filters onto it, and the database is only queried when you call something like .all, .first, or .each.