// SQL snippet

List triggers on a table

When rows change with no application code to blame, a trigger is usually the culprit. This recipe lists every trigger on one table with its full definition.

Main statement
PostgreSQL
Deckt außerdem ab
SQL Server MySQL SQLite

The task

Values in a table change although the codebase issues no matching INSERT or UPDATE. The next thing to inspect is the trigger list on that table.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.

PostgreSQL
SELECT t.tgname AS trigger_name,
       p.proname AS function_name,
       pg_get_triggerdef(t.oid) AS definition
FROM pg_trigger t
JOIN pg_proc p ON p.oid = t.tgfoid
WHERE t.tgrelid = 'public.users'::regclass
  AND NOT t.tgisinternal
ORDER BY t.tgname;

So funktioniert es

pg_trigger holds one row per trigger; tgisinternal filters out the system-managed ones such as the internal triggers that enforce foreign keys. pg_get_triggerdef renders the whole CREATE TRIGGER statement, including WHEN and transition-table clauses, and the joined pg_proc gives you the function to inspect next.

Variations

MySQL

MySQL
SELECT trigger_name, event_manipulation, action_timing,
       action_statement
FROM information_schema.triggers
WHERE event_object_schema = 'mydb'
  AND event_object_table = 'users';

SQLite

SQLite
SELECT name, sql
FROM sqlite_master
WHERE type = 'trigger' AND tbl_name = 'users';

SQL Server

SQL Server
SELECT t.name AS trigger_name,
       OBJECT_NAME(t.parent_id) AS table_name,
       te.type_desc AS firing_event,
       sm.definition
FROM sys.triggers t
JOIN sys.trigger_events te ON te.object_id = t.object_id
JOIN sys.sql_modules sm ON sm.object_id = t.object_id
WHERE t.parent_id = OBJECT_ID('dbo.Users');

Questions that come up

Why do rows update when no trigger seems to exist?

Look for foreign keys with ON DELETE CASCADE or ON UPDATE SET NULL pointing at the table, generated columns, rules (PostgreSQL's pg_rules), and triggers on other tables that write into this one. The query above only shows triggers attached to the named table.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.