Created
January 6, 2025 09:40
-
-
Save dinushchathurya/8b276a36c37ab68f9d451c138bc1a4be to your computer and use it in GitHub Desktop.
schema-changes-predicted.yaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Here is an example of a schema migration SQL file for a production database, following best practices: | |
Example: Adding a New Column to a Table | |
File: 2025_01_06_add_phone_to_users.sql | |
-- Migration: Add `phone` column to `users` table | |
-- Created on: 2025-01-06 | |
-- Author: Your Name | |
-- Description: Adds a nullable `phone` column to the `users` table for storing user phone numbers. | |
-- Start Transaction | |
START TRANSACTION; | |
-- Step 1: Check if the column already exists | |
DO | |
$$ | |
BEGIN | |
IF NOT EXISTS ( | |
SELECT 1 | |
FROM information_schema.columns | |
WHERE table_name = 'users' AND column_name = 'phone' | |
) THEN | |
-- Step 2: Add the new column | |
ALTER TABLE users ADD COLUMN phone VARCHAR(15) NULL COMMENT 'User phone number'; | |
END IF; | |
END; | |
$$; | |
-- Step 3: Commit the transaction | |
COMMIT; | |
--- | |
Explanation of the SQL Script: | |
1. Transaction Safety: | |
The script uses START TRANSACTION and COMMIT to ensure atomicity. If anything fails, the migration won't partially apply. | |
2. Idempotency: | |
Before altering the schema, the script checks if the column already exists. This avoids errors when the script is rerun. | |
3. Comments and Documentation: | |
Clearly state the purpose and author of the migration in comments. | |
4. Minimal Downtime: | |
Adding a new column is generally a fast operation, especially with NULL values (no default). Avoid operations like NOT NULL or default values unless necessary. | |
--- | |
Running in Production Safely: | |
Pre-deployment Checks: Test on a staging environment with production-like data. | |
Backup: Always take a database backup before applying migrations in production. | |
Monitoring: Observe query performance using monitoring tools (e.g., Datadog). | |
--- | |
Would you like an example for more complex migrations (e.g., large table splitting, index creation, etc.) or a guide on automating schema migrations? | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment