SQL Practice Logo

SQLPractice Online

Triggers & Stored Procedures: Concept

Module: Schema Design & Advanced DDL

Triggers are automatic actions that fire when specific database events occur (INSERT, UPDATE, DELETE). They execute SQL code without explicit calls from application code.

Think of triggers as event listeners in the database. When something happens (a row is inserted), the trigger "hears" it and responds automatically. The application doesn't need to know the trigger exists.

Stored procedures are reusable SQL functions that encapsulate complex logic. Unlike triggers, they must be called explicitly. They're like functions in programming languages, but they run inside the database.

Key differences:

**Triggers:**

- Fire automatically on events

- Cannot be called directly

- Execute within the same transaction

- Hidden from application code

- Hard to debug

**Stored Procedures:**

- Must be called explicitly

- Can be called from application or other procedures

- Can start their own transactions

- Visible in application code

- Easier to debug

**When to use triggers:**

- Audit logging (every change must be logged)

- Maintaining denormalized data (automatic consistency)

- Complex validation (beyond CHECK constraints)

- Cascading updates across tables

- Event notifications

**When to use stored procedures:**

- Complex business logic that belongs in database

- Batch operations (bulk updates, data migrations)

- Reducing network traffic (multiple queries in one call)

- Encapsulating complex queries for reuse

**When to use neither:**

- Simple CRUD operations (use application code)

- Business logic that changes frequently (use application code)

- Logic that needs to be tested independently (use application code)

## Trigger Types

### BEFORE Triggers

Execute before the operation. Can modify the data being inserted/updated or prevent the operation entirely.

**Use cases:**

- Validate data (beyond CHECK constraints)

- Modify data before insert (normalize phone numbers, trim whitespace)

- Prevent invalid operations (reject negative balances)

**Example:**

```sql