Full answer
sql
CREATE TABLE users (email TEXT);
CREATE TRIGGER users_email BEFORE INSERT ON users
WHEN NEW.email NOT LIKE '%_@_%'
BEGIN SELECT RAISE(ABORT, 'invalid email'); END;
INSERT INTO users VALUES ('not-an-email');
-- error on purposetext
Error: invalid emailThe message from RAISE reaches the application as the error text. Nothing was inserted:
sql
SELECT COUNT(*) AS rows_stored FROM users;| rows_stored |
|---|
| 0 |
RAISE(IGNORE) skips the offending row without an error, which is easy to miss:
sql
CREATE TABLE u2 (email TEXT);
CREATE TRIGGER u2_email BEFORE INSERT ON u2
WHEN NEW.email NOT LIKE '%_@_%'
BEGIN SELECT RAISE(IGNORE); END;
INSERT INTO u2 VALUES ('bad'), ('ok@example.com');
SELECT email FROM u2;| ok@example.com |
The bad email was dropped silently, and only the good row remains. Prefer ABORT for validation, so callers know the write failed, and prefer plain CHECK constraints when the rule only looks at the row itself.
sql
-- error on purpose
CREATE TABLE users (email TEXT);
CREATE TRIGGER users_email BEFORE INSERT ON users
WHEN NEW.email NOT LIKE '%_@_%'
BEGIN SELECT RAISE(ABORT, 'invalid email'); END;
INSERT INTO users VALUES ('not-an-email');
SELECT COUNT(*) AS rows_stored FROM users;
CREATE TABLE u2 (email TEXT);
CREATE TRIGGER u2_email BEFORE INSERT ON u2
WHEN NEW.email NOT LIKE '%_@_%'
BEGIN SELECT RAISE(IGNORE); END;
INSERT INTO u2 VALUES ('bad'), ('ok@example.com');
SELECT email FROM u2;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- RAISE(ABORT) cancels the statement with a message
- RAISE(IGNORE) skips the row silently
- RAISE(ROLLBACK) ends the whole transaction
- Use CHECK for simple single-row rules
Common mistakes
- Using IGNORE and losing rows without notice
- Writing triggers for rules a CHECK can express
Follow-ups
- How would PostgreSQL raise a custom error in a trigger?
- When would RAISE(FAIL) be useful?
Tips
- Contrast ABORT and IGNORE