SQLite เป็นฐานข้อมูลที่มีการใช้งาน มากที่สุดในโลก ด้วยจำนวนมากกว่า 1 ล้านล้านสำเนา (Trillion copies) ที่ทำงานอยู่ในอุปกรณ์ต่างๆ ทั่วโลก ตั้งแต่สมาร์ทโฟน, เว็บเบราว์เซอร์, IoT devices ไปจนถึง Desktop applications ในปี 2026 SQLite กำลังถูกนำไปใช้ในบทบาทใหม่ๆ เช่น Edge computing, Serverless applications และ Embedded analytics
SQLite Overview — ภาพรวม
SQLite เป็น Serverless, Self-contained, Zero-configuration database engine ที่เก็บข้อมูลทั้งหมดใน ไฟล์เดียว ไม่ต้องติดตั้ง Server ไม่ต้อง Config อะไร แค่เรียกใช้ Library ก็ใช้ได้ทันที:
| คุณสมบัติ | รายละเอียด |
|---|---|
| ขนาด Library | ~700 KB (เล็กมาก) |
| Architecture | Serverless — ไม่ต้องรัน Process แยก |
| Storage | Single-file — ฐานข้อมูลทั้งหมดอยู่ในไฟล์ .db ไฟล์เดียว |
| Configuration | Zero-configuration — ไม่ต้องตั้งค่าอะไร |
| SQL Support | มาตรฐาน SQL-92 เกือบครบ + Extensions |
| License | Public Domain — ใช้ฟรีทุกวัตถุประสงค์ |
| Max Database Size | 281 TB (ในทางทฤษฎี) |
| Concurrent Reads | ไม่จำกัด (WAL mode) |
| Concurrent Writes | 1 ครั้ง (Single writer) |
SQLite อยู่ทุกที่ — Everywhere
คุณใช้ SQLite ทุกวันโดยไม่รู้ตัว:
- สมาร์ทโฟน: ทั้ง Android และ iOS ใช้ SQLite เป็น Default database ทุก App ที่เก็บข้อมูลมักใช้ SQLite (Contacts, Messages, Photos metadata)
- เว็บเบราว์เซอร์: Chrome, Firefox, Safari ใช้ SQLite เก็บ Bookmarks, History, Cookies, Cache
- Desktop Apps: Skype, iTunes, Dropbox, Adobe Lightroom ทั้งหมดใช้ SQLite
- IoT Devices: Smart TV, เครื่องเล่น, อุปกรณ์ Embedded ใช้ SQLite เพราะเล็กและไม่ต้องรัน Server
- ระบบปฏิบัติการ: macOS, iOS, Android ใช้ SQLite เป็นส่วนหนึ่งของ OS
- Git: git ใช้ SQLite สำหรับบาง Internal operations
SQLite vs PostgreSQL vs MySQL — เมื่อไหร่ใช้อะไร
| คุณสมบัติ | SQLite | PostgreSQL | MySQL |
|---|---|---|---|
| Architecture | Embedded (Serverless) | Client-Server | Client-Server |
| Setup | ไม่ต้อง Setup | ต้องติดตั้ง Server | ต้องติดตั้ง Server |
| Concurrency | Single writer + Multiple readers | Multiple writers + readers | Multiple writers + readers |
| Max size (จริง) | เหมาะกับ < 1 GB | ไม่จำกัด | ไม่จำกัด |
| Users | ไม่มี User management | มี Roles & Permissions | มี Users & Grants |
| Network Access | ไม่มี (Local file only) | TCP/IP | TCP/IP |
| เหมาะกับ | Embedded, Mobile, Desktop, Testing, Edge, IoT | Enterprise, Web apps, Analytics | Web apps, CMS (WordPress) |
SQLite Features ที่ทรงพลังในปี 2026
WAL Mode (Write-Ahead Logging)
WAL mode ทำให้ SQLite รองรับ Concurrent reads ได้ดีขึ้นมาก โดย Readers ไม่ Block writers และ Writers ไม่ Block readers:
-- เปิด WAL mode (ทำครั้งเดียว ติดไปตลอด)
PRAGMA journal_mode=WAL;
-- ตรวจสอบ Journal mode
PRAGMA journal_mode;
-- WAL mode ดียังไง:
-- 1. อ่านและเขียนพร้อมกันได้
-- 2. เร็วกว่า DELETE mode (default) สำหรับ Write
-- 3. Database file ไม่ถูก Lock ระหว่าง Read
-- 4. Crash recovery ดีกว่า
FTS5 (Full-Text Search)
SQLite มี Full-text search engine ในตัว ไม่ต้องใช้ Elasticsearch:
-- สร้าง FTS5 Table
CREATE VIRTUAL TABLE articles USING fts5(title, content, tags);
-- เพิ่มข้อมูล
INSERT INTO articles VALUES(
'Docker Security Best Practices',
'Docker Security คือแนวทางปฏิบัติ...',
'docker security container'
);
-- ค้นหา Full-text (เร็วมาก)
SELECT * FROM articles WHERE articles MATCH 'docker security';
-- ค้นหาแบบ Phrase
SELECT * FROM articles WHERE articles MATCH '"best practices"';
-- Ranking ผลลัพธ์ (BM25)
SELECT *, rank FROM articles WHERE articles MATCH 'docker'
ORDER BY rank;
JSON Support
-- SQLite รองรับ JSON ตั้งแต่ 3.38+ (2022)
-- เก็บ JSON ในคอลัมน์ TEXT ปกติ
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name TEXT,
metadata JSON -- เก็บ JSON
);
INSERT INTO products VALUES(1, 'Server', '{"cpu": 8, "ram": 32, "tags": ["web", "api"]}');
-- Query JSON fields
SELECT name, json_extract(metadata, '$.cpu') as cpu
FROM products
WHERE json_extract(metadata, '$.ram') >= 16;
-- JSON array operations
SELECT name FROM products
WHERE json_each.value = 'web'
AND json_each.key IN (
SELECT key FROM json_each(json_extract(metadata, '$.tags'))
);
Window Functions, CTE, Triggers
-- CTE (Common Table Expressions) — Recursive
WITH RECURSIVE fibonacci(n, fib_n, fib_n1) AS (
SELECT 1, 0, 1
UNION ALL
SELECT n+1, fib_n1, fib_n + fib_n1 FROM fibonacci WHERE n < 10
)
SELECT n, fib_n FROM fibonacci;
-- Window Functions
SELECT
date,
sales,
AVG(sales) OVER (ORDER BY date ROWS 6 PRECEDING) as moving_avg_7d,
SUM(sales) OVER (PARTITION BY strftime('%Y-%m', date)) as monthly_total,
ROW_NUMBER() OVER (ORDER BY sales DESC) as rank
FROM daily_sales;
-- Triggers
CREATE TRIGGER update_timestamp
AFTER UPDATE ON articles
BEGIN
UPDATE articles SET updated_at = datetime('now') WHERE id = NEW.id;
END;
SQLite ใน Web Apps — Turso, Litestream, LiteFS
Turso / libSQL
Turso คือ Managed SQLite service ที่ทำให้ SQLite ใช้ได้ใน Web apps แบบ Multi-region ด้วย libSQL (Fork ของ SQLite ที่รองรับ Network access):
# ติดตั้ง Turso CLI
curl -sSfL https://get.tur.so/install.sh | bash
turso auth signup
# สร้าง Database
turso db create my-app
turso db show my-app
# ใช้ใน Node.js
npm install @libsql/client
// app.js
import { createClient } from "@libsql/client";
const db = createClient({
url: "libsql://my-app-username.turso.io",
authToken: "your-token"
});
const result = await db.execute("SELECT * FROM users WHERE id = ?", [1]);
console.log(result.rows);
Litestream — Continuous Replication
Litestream ทำ Continuous replication ของ SQLite ไป S3 หรือ Object storage เพื่อ Backup อัตโนมัติ:
# ติดตั้ง Litestream
wget https://github.com/benbjohnson/litestream/releases/download/v0.3.13/litestream-v0.3.13-linux-amd64.tar.gz
tar -xzf litestream-v0.3.13-linux-amd64.tar.gz
# litestream.yml config
dbs:
- path: /data/app.db
replicas:
- type: s3
bucket: my-backups
path: app.db
region: ap-southeast-1
retention: 72h
# รัน Application ผ่าน Litestream
litestream replicate -config litestream.yml
# Restore จาก S3
litestream restore -config litestream.yml /data/app.db
SQLite กับ ORMs ยอดนิยม
// Drizzle ORM (ยอดนิยม 2026)
import { drizzle } from "drizzle-orm/better-sqlite3";
import Database from "better-sqlite3";
const sqlite = new Database("app.db");
const db = drizzle(sqlite);
const users = await db.select().from(usersTable).where(eq(usersTable.age, 25));
// Prisma
// schema.prisma
datasource db {
provider = "sqlite"
url = "file:./app.db"
}
// better-sqlite3 (Direct — เร็วที่สุด)
import Database from "better-sqlite3";
const db = new Database("app.db", { readonly: false });
db.pragma("journal_mode = WAL");
db.pragma("synchronous = NORMAL");
const stmt = db.prepare("SELECT * FROM users WHERE id = ?");
const user = stmt.get(userId);
SQLite สำหรับ Testing
SQLite เหมาะสำหรับ In-memory testing เพราะเร็วมากและไม่ต้อง Setup database server:
// In-memory SQLite สำหรับ Test
import Database from "better-sqlite3";
describe("User Service", () => {
let db;
beforeEach(() => {
db = new Database(":memory:"); // In-memory — เร็วมาก
db.exec(`
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
INSERT INTO users VALUES(1, 'Test User', 'test@example.com');
`);
});
afterEach(() => {
db.close();
});
test("should find user by id", () => {
const user = db.prepare("SELECT * FROM users WHERE id = ?").get(1);
expect(user.name).toBe("Test User");
});
});
SQLite Limits — ข้อจำกัดและเมื่อควร Upgrade
| ข้อจำกัด | ขีดจำกัด | เมื่อไหร่ต้องเปลี่ยน |
|---|---|---|
| Concurrent Writes | 1 writer ต่อครั้ง | ถ้าต้องการ > 100 writes/second จากหลาย Client |
| Database Size | ~1-10 GB (ประสิทธิภาพดี) | ถ้าข้อมูลเกิน 10 GB ควรพิจารณา PostgreSQL |
| Network Access | ไม่มี (Local only) | ถ้าต้องการ Remote access (ใช้ Turso/libSQL) |
| User Management | ไม่มี | ถ้าต้องการ Multi-user authentication |
| Replication | ไม่มี Built-in | ถ้าต้องการ Real-time replication (ใช้ Litestream) |
SQLite Performance Tuning — PRAGMA
-- Performance PRAGMAs สำหรับ Production
PRAGMA journal_mode = WAL; -- เปิด WAL mode
PRAGMA synchronous = NORMAL; -- ลด Disk I/O (ยอมรับความเสี่ยง Power failure เล็กน้อย)
PRAGMA cache_size = -64000; -- 64 MB cache (default 2 MB)
PRAGMA temp_store = MEMORY; -- ใช้ RAM สำหรับ Temp tables
PRAGMA mmap_size = 268435456; -- 256 MB memory-mapped I/O
PRAGMA page_size = 4096; -- 4 KB page size (match OS)
PRAGMA busy_timeout = 5000; -- รอ 5 วินาทีถ้า Database locked
PRAGMA foreign_keys = ON; -- เปิด Foreign key constraints
-- Optimize สำหรับ Read-heavy workloads
PRAGMA optimize; -- ให้ SQLite optimize เอง (รันเมื่อปิด Connection)
-- ตรวจสอบ Integrity
PRAGMA integrity_check; -- ตรวจสอบว่า Database ไม่เสียหาย
SQLite Backup Strategies
# วิธี 1: SQLite .backup command (ปลอดภัยที่สุด)
sqlite3 app.db ".backup /backup/app-$(date +%Y%m%d).db"
# วิธี 2: VACUUM INTO (สร้าง Copy ที่ Compact)
sqlite3 app.db "VACUUM INTO '/backup/app-compact.db';"
# วิธี 3: cp (ปลอดภัยเฉพาะใน WAL mode เมื่อไม่มีการเขียน)
# ไม่แนะนำ ใช้ .backup แทน
# วิธี 4: Litestream (Continuous backup to S3)
# ดูหัวข้อ Litestream ด้านบน
# Cron job สำหรับ Daily backup
# crontab -e
0 3 * * * sqlite3 /data/app.db ".backup /backup/app-$(date +%%Y%%m%%d).db" && gzip /backup/app-$(date +%%Y%%m%%d).db
SQLite + Cloudflare D1
Cloudflare D1 คือ Serverless SQLite database ที่ทำงานบน Cloudflare's Edge network ทำให้ Database อยู่ใกล้ User ที่สุด:
# สร้าง D1 Database
npx wrangler d1 create my-app-db
# wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "my-app-db"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
// Cloudflare Worker กับ D1
export default {
async fetch(request, env) {
const { results } = await env.DB.prepare(
"SELECT * FROM articles WHERE category = ?"
).bind("tech").all();
return Response.json(results);
}
};
// Migration
// migrations/0001_init.sql
CREATE TABLE articles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT,
category TEXT,
created_at TEXT DEFAULT (datetime('now'))
);
# Apply migration
npx wrangler d1 migrations apply my-app-db
Embedded Analytics กับ SQLite
SQLite เหมาะสำหรับ Embedded analytics ใน Application เช่น Dashboard, Reporting, Data exploration โดยไม่ต้องพึ่ง External database:
-- Analytics queries ที่ SQLite ทำได้ดี
-- Daily active users
SELECT date(created_at) as day, COUNT(DISTINCT user_id) as dau
FROM events
WHERE created_at >= date('now', '-30 days')
GROUP BY date(created_at)
ORDER BY day;
-- Retention analysis
WITH first_visit AS (
SELECT user_id, MIN(date(created_at)) as first_day
FROM events GROUP BY user_id
)
SELECT
f.first_day as cohort,
julianday(date(e.created_at)) - julianday(f.first_day) as day_n,
COUNT(DISTINCT e.user_id) as users
FROM events e
JOIN first_visit f ON e.user_id = f.user_id
GROUP BY cohort, day_n;
-- Top pages with percentile
SELECT
page,
COUNT(*) as views,
AVG(load_time) as avg_load,
-- Percentile approximation
json_group_array(load_time) as all_times
FROM page_views
GROUP BY page
ORDER BY views DESC
LIMIT 20;
สรุป — SQLite ในปี 2026
SQLite ไม่ใช่แค่ "ฐานข้อมูลตัวเล็กๆ" อีกต่อไป ในปี 2026 SQLite กำลังเป็น Foundation ของ Edge computing และ Modern web applications ด้วย Turso/libSQL ที่ทำให้ SQLite ใช้ได้แบบ Distributed, Litestream ที่ทำ Continuous backup, และ Cloudflare D1 ที่เป็น Serverless SQLite บน Edge
สำหรับ Project ใหม่ในปี 2026 ถ้า Application ของคุณเป็น Read-heavy, Single-user, หรือ Embedded ลองพิจารณา SQLite ก่อน PostgreSQL เพราะ Setup ง่ายกว่า, Deploy ง่ายกว่า (แค่ Copy ไฟล์), Backup ง่ายกว่า และ Performance สำหรับ Use case ที่เหมาะสมนั้น เร็วกว่า Client-server database ด้วยซ้ำ
