General Best Practices
Data Management Best Practices
Data Management Best Practices
Effective data management balances operational efficiency with data safety. This guide covers essential practices for managing data safely and effectively using WhoDB, from routine operations to complex data transformations.
Data Safety Principles
Always Backup Before Changes
The most important rule of data management is simple: always have a backup before making changes.
Types of Changes Requiring Backups:
- Bulk updates or deletes
- Schema modifications
- Data migrations
- Testing new queries on production data
- Running unfamiliar scripts
- Major application updates
Backup Strategies:
- Full database backup for major changes
- Table-level backup for isolated changes
- Row-level backup for small, targeted changes
- Transaction savepoints for multi-step operations
Creating Backups:
PostgreSQL:
Bash
# Full database backup pg_dump -h localhost -U username -d database_name > backup_$(date +%Y%m%d_%H%M%S).sql # Single table backup pg_dump -h localhost -U username -d database_name -t table_name > table_backup.sql # Compressed backup pg_dump -h localhost -U username -d database_name | gzip > backup.sql.gz
MySQL:
Bash
# Full database backup mysqldump -h localhost -u username -p database_name > backup_$(date +%Y%m%d_%H%M%S).sql # Single table backup mysqldump -h localhost -u username -p database_name table_name > table_backup.sql # All databases mysqldump -h localhost -u username -p --all-databases > all_databases_backup.sql
MongoDB:
Bash
# Full database backup mongodump --host localhost --port 27017 --db database_name --out /backup/location # Single collection backup mongodump --host localhost --db database_name --collection collection_name --out /backup/location
Verify Backups
Backups are only useful if they can be restored successfully.
Backup Verification Process:
- Create test database or schema
- Restore backup to test location
- Verify data integrity
- Test critical queries
- Document verification date
- Automate verification where possible
Regular Testing Schedule:
- Test restore procedures monthly
- Verify backup completeness
- Measure restoration time
- Update recovery documentation
- Train team members on restoration
Use Transactions Appropriately
Transactions ensure data consistency by treating multiple operations as a single unit of work.
Transaction Basics:
sql
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; -- Verify changes before committing SELECT id, balance FROM accounts WHERE id IN (1, 2); -- If correct: COMMIT; -- If incorrect: ROLLBACK;
When to Use Transactions:
- Multiple related updates
- Data migrations
- Batch operations
- Testing complex queries
- Any operation that must be atomic
Transaction Best Practices:
- Keep transactions short
- Avoid user interaction during transactions
- Don't hold transactions during long operations
- Use appropriate isolation levels
- Monitor for deadlocks
Safe Data Modification
Test Queries Before Execution
Always test data modification queries before running them on production data.
Safe Testing Workflow:
- Select Before Update/Delete:
sql
-- First, SELECT to see what will be affected SELECT * FROM users WHERE last_login < '2020-01-01'; -- Review the results, then execute the update -- UPDATE users SET active = false WHERE last_login < '2020-01-01';
- Use Transactions for Testing:
sql
BEGIN; UPDATE products SET price = price * 1.10 WHERE category = 'electronics'; -- Review the changes SELECT id, name, price FROM products WHERE category = 'electronics'; -- If correct: COMMIT; otherwise: ROLLBACK; ROLLBACK;
- Test on Subset First:
sql
-- Test on small subset UPDATE orders SET status = 'archived' WHERE order_date < '2020-01-01' LIMIT 10; -- If successful, run on full dataset -- UPDATE orders SET status = 'archived' WHERE order_date < '2020-01-01';
Use WHERE Clauses Carefully
Missing or incorrect WHERE clauses cause some of the most devastating data loss incidents.
Dangerous Patterns:
sql
-- DANGER: Missing WHERE clause updates all rows UPDATE users SET role = 'admin'; -- DANGER: Incorrect logic updates wrong rows UPDATE products SET discontinued = true WHERE active = true; -- (Should be: WHERE active = false)
Safety Measures:
- Always write WHERE clause first
- Use SELECT to verify WHERE logic
- Double-check column names and values
- Use transactions for reversibility
- Limit rows affected during testing
Implement Row-Level Verification
For critical updates, verify each affected row.
Verification Query Pattern:
sql
-- Create temporary backup table CREATE TABLE orders_backup AS SELECT * FROM orders WHERE status = 'pending'; -- Perform update UPDATE orders SET status = 'processing', updated_at = CURRENT_TIMESTAMP WHERE status = 'pending'; -- Verify changes SELECT b.id, b.status as old_status, o.status as new_status FROM orders_backup b JOIN orders o ON b.id = o.id WHERE b.status != o.status; -- If incorrect, rollback using backup table -- If correct, drop backup table DROP TABLE orders_backup;
Bulk Operations
Planning Bulk Operations
Bulk operations require careful planning to avoid impacting system performance.
Pre-Operation Checklist:
- Backup created and verified
- Operation tested on subset
- Maintenance window scheduled
- Rollback plan documented
- Monitoring in place
- Stakeholders notified
- Resource requirements assessed
Batch Processing
Process large datasets in batches to avoid locking tables and consuming excessive resources.
Batch Update Pattern:
sql
-- Process in batches of 1000 rows DO $ DECLARE batch_size INTEGER := 1000; processed INTEGER := 0; total INTEGER; BEGIN SELECT COUNT(*) INTO total FROM users WHERE active = false; WHILE processed < total LOOP UPDATE users SET archived = true WHERE id IN ( SELECT id FROM users WHERE active = false AND archived = false LIMIT batch_size ); processed := processed + batch_size; -- Short delay to reduce system load PERFORM pg_sleep(0.1); RAISE NOTICE 'Processed % of % rows', processed, total; END LOOP; END $;
Benefits of Batch Processing:
- Reduces lock contention
- Allows concurrent operations
- Easier to monitor progress
- Can be paused and resumed
- Lower memory usage
Handling Large Deletes
Large delete operations can cause performance issues and transaction log growth.
Incremental Delete Strategy:
sql
-- Delete in chunks DELETE FROM logs WHERE id IN ( SELECT id FROM logs WHERE created_at < '2020-01-01' LIMIT 10000 ); -- Repeat until done -- Monitor table size reduction: SELECT COUNT(*) FROM logs;
Truncate for Full Table Deletion:
sql
-- Much faster than DELETE for removing all rows TRUNCATE TABLE staging_data; -- Truncate with cascade for related tables TRUNCATE TABLE orders CASCADE;
Data Validation
Input Validation
Validate data before insertion or update to maintain data quality.
Validation Checks:
Data Type Validation:
sql
-- Ensure numeric values are within range SELECT * FROM products WHERE price < 0 OR price > 1000000; -- Check date validity SELECT * FROM events WHERE event_date > CURRENT_DATE + INTERVAL '10 years';
Format Validation:
sql
-- Validate email format SELECT * FROM users WHERE email !~ '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}