SQLite
Updated: September 10, 2025Categories: Query, Backend
Printed from:
SQLite Comprehensive Cheatsheet
1. Connection and Basic Commands
CLI Connection
Bash
123456# Open SQLite shell
sqlite3 database.db
# Execute SQL from command line
sqlite3 database.db "SELECT * FROM users;"
Programmatic Connections
Python (sqlite3)
Python
1234567891011121314import sqlite3
# Create/Connect to database
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
# Execute query
cursor.execute('SELECT * FROM users')
results = cursor.fetchall()
# Commit and close
conn.commit()
conn.close()
JavaScript (Node.js with better-sqlite3)
JavaScript
123456789101112const Database = require('better-sqlite3');
const db = new Database('database.db');
// Simple query
const users = db.prepare('SELECT * FROM users').all();
// Transaction
const insert = db.prepare('INSERT INTO users (name) VALUES (?)');
const insertMany = db.transaction((users) => {
for (const user of users) insert.run(user);
});
2. Database Operations
Create Database
SQL
123-- Creates a new database (or opens if exists)
sqlite3 newdatabase.db
Attach and Detach Databases
SQL
12345678910-- Attach another database
ATTACH DATABASE 'secondary.db' AS secondary;
-- Query across databases
SELECT * FROM main.users u
JOIN secondary.orders o ON u.id = o.user_id;
-- Detach database
DETACH DATABASE secondary;
3. Table Operations
Create Table
SQL
1234567CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
email TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Alter Table
SQL
123456-- Add column
ALTER TABLE users ADD COLUMN last_login DATETIME;
-- Rename table
ALTER TABLE users RENAME TO app_users;
Drop Table
SQL
123-- Drop table
DROP TABLE IF EXISTS users;
4. SQLite Data Types and Affinity
Supported Data Types
NULL: Null valueINTEGER: Signed integer (1, 2, 3, 4, 6, or 8 bytes)REAL: 8-byte floating-pointTEXT: Text string, UTF-8/16BLOB: Binary large object
Type Affinity Rules
TEXTAffinityNUMERICAffinityINTEGERAffinityREALAffinityBLOBAffinity
5. CRUD Operations
Insert
SQL
123456789-- Single insert
INSERT INTO users (username, email)
VALUES ('johndoe', 'john@example.com');
-- Multiple insert
INSERT INTO users (username, email) VALUES
('alice', 'alice@example.com'),
('bob', 'bob@example.com');
Select
SQL
1234567891011-- Basic select
SELECT * FROM users;
-- Filtered select
SELECT username, email FROM users
WHERE created_at > date('now', '-30 days');
-- Pagination
SELECT * FROM users
LIMIT 10 OFFSET 20;
Update
SQL
12345-- Update specific rows
UPDATE users
SET last_login = CURRENT_TIMESTAMP
WHERE username = 'johndoe';
Delete
SQL
1234-- Delete specific rows
DELETE FROM users
WHERE id = 5;
6. Joins and Relationships
Inner Join
SQL
1234SELECT u.username, o.order_id
FROM users u
INNER JOIN orders o ON u.id = o.user_id;
Left Join
SQL
1234SELECT u.username, o.order_id
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;
7. Indexes and Constraints
Create Index
SQL
123456-- Simple index
CREATE INDEX idx_username ON users(username);
-- Unique index
CREATE UNIQUE INDEX idx_email ON users(email);
Constraints
SQL
12345678CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price REAL CHECK (price > 0),
category TEXT DEFAULT 'Misc',
UNIQUE(name, category)
);
8. Functions and Operators
String Functions
SQL
1234567-- Concatenation, substring, length
SELECT
name || ' ' || lastname AS full_name,
substr(name, 1, 3) AS first_three,
length(name) AS name_length
FROM users;
Date and Time
SQL
123456-- Current timestamp
SELECT datetime('now');
-- Date calculations
SELECT date('now', '+1 month');
9. SQLite-Specific Features
Full-Text Search
SQL
123456-- Create FTS table
CREATE VIRTUAL TABLE docs USING fts5(title, content);
-- Search
SELECT * FROM docs WHERE docs MATCH 'sqlite tutorial';
Triggers
SQL
1234567CREATE TRIGGER update_timestamp
AFTER UPDATE ON users
BEGIN
UPDATE users SET updated_at = CURRENT_TIMESTAMP
WHERE id = NEW.id;
END;
10. Pragma Commands
SQL
123456789-- Check journal mode
PRAGMA journal_mode;
-- Set journal mode
PRAGMA journal_mode = WAL;
-- Cache size
PRAGMA cache_size = -2000; -- 2MB cache
11. Performance Optimization
WAL Mode
SQL
123-- Enable Write-Ahead Logging
PRAGMA journal_mode = WAL;
Batch Transactions
SQL
1234BEGIN TRANSACTION;
-- Multiple insert/update operations
COMMIT;
12. Mobile/Desktop Patterns
Connection Pooling
Python
12345678910111213# Python example with connection pool
import sqlite3
class DatabaseManager:
def __init__(self, db_path):
self.db_path = db_path
self.conn = None
def get_connection(self):
if not self.conn:
self.conn = sqlite3.connect(self.db_path)
return self.conn
13. Backup and Migration
Backup Database
Bash
123# CLI Backup
sqlite3 source.db ".backup destination.db"
SQL
123-- SQL Backup
BACKUP DATABASE TO 'backup.db';
Restore/Migrate
Bash
123# Restore from backup
sqlite3 destination.db ".restore backup.db"
Best Practices
- Use WAL journal mode for better concurrency
- Enable foreign key constraints
- Use transactions for batch operations
- Create appropriate indexes
- Limit result sets
- Use prepared statements
Recommended Tools
- DB Browser for SQLite
- SQLite Browser (VS Code Extension)
- sqlite3 CLI
- SQLite Expert Professional
Performance Tips for Embedded Use
- Keep transactions short
- Use prepared statements
- Minimize disk I/O
- Use appropriate indexing
- Monitor and analyze query performance
Continue Learning
Discover more cheatsheets to boost your productivity