Sub topic 17
Maintenance and Upgrades
Assume you are comfortable with Linux package managers, systemctl, basic SQL, backups, and editing configuration files with sudo. Maintenance keeps the database responsive and reduces the risk of losing data during an upgrade.
Routine maintenance
A database stores more than table rows. It also maintains indexes, statistics, transaction metadata, and log files. These items need regular attention.
For PostgreSQL, VACUUM reclaims space from rows that are no longer visible to active transactions. ANALYZE updates statistics that the query planner uses to choose efficient execution plans. Autovacuum normally runs both tasks, but you should monitor it rather than disable it.
For MySQL with InnoDB, background processes handle much of the cleanup. Check table growth, unused indexes, transaction history, and backup space. OPTIMIZE TABLE can rebuild a table and may use substantial disk space or cause locking, so run it only after checking its engine-specific behavior.
Review logs, disk usage, failed backups, replication delay, and connection usage on a schedule.
# Package and service checks
sudo apt update
apt list --upgradable
sudo systemctl status postgresql
# PostgreSQL maintenance
sudo -u postgres psql -d appdb -c 'VACUUM (ANALYZE);'
# Check storage before maintenance or an upgrade
df -h
sudo du -sh /var/lib/postgresql /var/lib/mysql 2>/dev/nullPlanning an upgrade
Distribution packages usually provide two upgrade types:
- A minor upgrade fixes bugs and security problems within a major release. It is usually compatible with existing data and may require a service restart.
- A major upgrade changes the database version or behavior. It needs a tested migration plan and may require downtime.
Before changing packages, record the current version, configuration paths, extensions, users, scheduled jobs, and application connection settings. Confirm that the application and every extension support the target version.
Take a fresh backup and verify that it restores. Keep enough free disk space for temporary files and, when possible, a rollback copy or a separate test host. Test the upgrade with a production-like database before scheduling the change.
# Record versions and package state
psql --version
mysql --version
dpkg -l | grep -E 'postgresql|mysql'
# Apply ordinary package updates
sudo apt update
sudo apt upgrade
# Restart only when the package or maintenance plan requires it
sudo systemctl restart postgresql
sudo systemctl status postgresqlPostgreSQL major upgrades can use pg_upgrade or logical dump and restore. MySQL upgrades must follow the supported version path and vendor checks. Do not copy a data directory between incompatible major versions.
Exercise
Why should a major upgrade be tested with production-like data instead of only an empty database?
Show answer
Data volume, extensions, indexes, queries, permissions, and application behavior can expose upgrade problems that an empty database cannot reveal.