Database Maintenance
Website databases store important information such as user accounts, articles, product records, application settings and transaction data.
Without regular maintenance, a database may become unnecessarily large, slow, inconsistent or vulnerable to data loss.
In this intermediate course, you will learn how to inspect and maintain MySQL or MariaDB databases using tools such as phpMyAdmin and SQL commands. You will also learn how to create reliable backups, restore data, optimise tables, review indexes, remove unnecessary records, check data integrity and troubleshoot common database problems while protecting production information.
Learning Outcomes
What you will be able to do after completing this course.
By the end of this course, you should be able to inspect, back up, optimise, secure, troubleshoot and document a website database safely.
- Explain why regular database maintenance matters.
- Identify databases, tables, rows, columns, indexes and relationships.
- Understand the differences between MySQL and MariaDB.
- Access and navigate phpMyAdmin.
- Review database names, structures, engines and character sets.
- Identify unusually large or rapidly growing tables.
- Create a complete backup before maintenance.
- Export databases in SQL format.
- Create compressed backups.
- Restore a database from SQL.
- Verify that a backup can be imported.
- Compare full, incremental and scheduled backups.
- Create a backup-retention schedule.
- Inspect tables for errors or corruption.
- Use table checking and repair tools where supported.
- Optimise tables and recover unused space.
- Understand table fragmentation.
- Review indexes and query performance.
- Identify missing, duplicate or unnecessary indexes.
- Use SELECT, WHERE, ORDER BY and LIMIT safely.
- Use COUNT() and aggregate functions.
- Identify duplicate, incomplete and invalid records.
- Remove obsolete data cautiously.
- Clean sessions, logs, caches and temporary data.
- Understand DELETE, UPDATE, DROP and TRUNCATE risks.
- Use transactions where supported.
- Understand primary and foreign keys.
- Identify orphaned records.
- Review character sets and collations.
- Identify multilingual encoding problems.
- Monitor storage growth.
- Review slow queries and bottlenecks.
- Use EXPLAIN.
- Avoid unnecessary columns and excessive result sets.
- Review database users and privileges.
- Apply least privilege.
- Remove unused accounts and rotate exposed credentials.
- Protect configuration files.
- Avoid risky work without a tested backup.
- Test significant changes in staging.
- Use website maintenance mode when needed.
- Troubleshoot connection and authentication errors.
- Resolve import size, timeout and compatibility issues.
- Document maintenance and structural changes.
- Create a recurring maintenance checklist.
- Verify website functionality after maintenance.
Course Roadmap
Follow the maintenance sequence or select a lesson to review.
Understanding Website Databases
Review the structures that store website information.
Database
A structured collection containing related application data.
Table
A collection of records organised into rows and columns.
Index
A structure that helps the database locate records efficiently.
Why Maintenance Matters
- Protects important information from accidental loss.
- Reduces unnecessary storage usage.
- Helps maintain query performance.
- Detects corruption and inconsistent records.
- Improves security and account hygiene.
- Supports predictable recovery.
Practice Activity
- List five types of website data stored in a database.
- Define a table, row and column.
- Explain one reason an index improves performance.
Navigating MySQL, MariaDB and phpMyAdmin
Understand the database platform and management interface.
MySQL
A widely used relational database platform for websites and applications.
MariaDB
A closely related open-source database platform with broad MySQL compatibility.
phpMyAdmin Areas to Review
- Database list
- Table names
- Structure view
- Browse view
- SQL tab
- Export and Import
- Operations
- User accounts and privileges
Navigation Exercise
- Open a lab database in phpMyAdmin.
- Identify the storage engine and collation.
- Open Structure and Browse views.
- Locate Export and Import without running them yet.
Inspecting Database Structure and Growth
Identify large tables, storage engines and growth patterns.
Useful Inspection Query
SELECT
table_name,
engine,
table_rows,
ROUND(data_length / 1024 / 1024, 2) AS data_mb,
ROUND(index_length / 1024 / 1024, 2) AS index_mb
FROM information_schema.tables
WHERE table_schema = 'your_database'
ORDER BY data_length + index_length DESC;
What to Look For
- Tables much larger than expected
- Fast-growing log or session tables
- Unusual storage-engine differences
- Indexes larger than table data
- Unexpected character sets or collations
- Tables with very high row counts
Inspection Exercise
- List the five largest tables.
- Record their row counts and storage engines.
- Identify which tables are expected to grow.
- Document one table that needs further review.
Creating Reliable Database Backups
Export a complete SQL backup before maintenance.
phpMyAdmin Export Workflow
- Select the correct database.
- Open the Export tab.
- Choose SQL format.
- Select all required tables.
- Include structure and data.
- Choose compression where appropriate.
- Download the export.
- Record the date, source and purpose.
Command-Line Example
mysqldump \
--single-transaction \
--routines \
--triggers \
--events \
-u backup_user \
-p website_database \
> website_database_2026-08-06.sql
Backup Exercise
- Export a lab database in SQL format.
- Create a compressed copy.
- Name the file with database name and date.
- Record its file size and storage location.
Restoring and Verifying Database Backups
Confirm that a backup can be imported successfully.
Restore Workflow
- Create an empty test database.
- Confirm the required character set and collation.
- Open the Import tab.
- Select the SQL or compressed backup file.
- Start the import.
- Review errors and warnings.
- Compare table and row counts.
- Test the restored application where possible.
Command-Line Example
mysql \
-u restore_user \
-p restored_database \
< website_database_2026-08-06.sql
Restore Exercise
- Create an empty test database.
- Import the backup from the previous lesson.
- Compare table counts.
- Open several records.
- Document whether the restore succeeded.
Backup Types, Scheduling and Retention
Build a backup plan that balances recovery and storage.
| Type | Description |
|---|---|
| Full Backup | Contains the complete database at a point in time |
| Incremental Backup | Contains changes since a previous backup point |
| Scheduled Backup | Runs automatically according to a defined frequency |
| Pre-Change Backup | Created immediately before significant maintenance |
Example Retention Plan
- Daily backups retained for 14 days
- Weekly backups retained for 8 weeks
- Monthly backups retained for 12 months
- Pre-change backups retained until validation completes
- At least one protected off-server copy
Retention Exercise
- Define daily, weekly and monthly retention.
- Choose an off-server backup location.
- Define how often restores will be tested.
- Document who reviews backup failures.
Checking Tables for Errors
Inspect table health and use repair tools only where supported.
Check a Table
CHECK TABLE articles;
CHECK TABLE users;
CHECK TABLE transactions;
Repair Where Supported
REPAIR TABLE legacy_table;
REPAIR TABLE in the same way. Follow
engine-specific recovery procedures.
Good Practice
- Back up before repair operations.
- Review server logs.
- Confirm storage health.
- Do not repeatedly repair without identifying the cause.
- Test the application after recovery.
Table Health Exercise
- Check three lab tables.
- Record the status messages.
- Identify each table's storage engine.
- Document the correct recovery approach.
Optimising Tables and Reclaiming Space
Understand fragmentation and storage recovery.
Optimise Example
OPTIMIZE TABLE sessions;
OPTIMIZE TABLE application_logs;
Why Tables Become Fragmented
- Large numbers of deleted records
- Frequent updates to variable-length fields
- Temporary and session data churn
- Log rotation and cleanup
- Major data imports followed by deletion
Optimisation Exercise
- Record table size before optimisation.
- Optimise a suitable lab table.
- Record the size afterward.
- Confirm that the website or test application still works.
Inspecting Data Safely with SQL
Use read-only queries to understand stored information.
Basic Inspection Queries
SELECT id, title, created_at
FROM articles
ORDER BY created_at DESC
LIMIT 20;
SELECT COUNT(*) AS total_users
FROM users;
SELECT status, COUNT(*) AS total
FROM orders
GROUP BY status
ORDER BY total DESC;
Find Potential Duplicate Values
SELECT email, COUNT(*) AS total
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
Inspection Exercise
- Display the latest ten records from a table.
- Count total rows.
- Count records by status.
- Search for duplicates in a non-sensitive test field.
Removing Obsolete and Temporary Records
Clean sessions, logs and caches without deleting required data.
Common Cleanup Targets
- Expired sessions
- Temporary records
- Old application logs
- Expired tokens
- Database-backed cache entries
- Stale import or queue records
Preview Before Delete
SELECT id, expires_at
FROM sessions
WHERE expires_at < NOW()
ORDER BY expires_at
LIMIT 100;
Controlled Delete Example
DELETE FROM sessions
WHERE expires_at < NOW()
LIMIT 1000;
DELETE, UPDATE, DROP and
TRUNCATE can cause irreversible loss. Verify the target,
back up first and test in staging.
Cleanup Exercise
- Identify one temporary-data table.
- Write a SELECT query for expired records.
- Count the affected rows.
- Perform the cleanup only in a lab database.
- Verify the application afterward.
Primary Keys, Foreign Keys and Orphaned Records
Protect relationships between connected tables.
Primary Key
Uniquely identifies each row in a table.
Foreign Key
Links a record to a related row in another table.
Find Orphaned Records
SELECT comments.id, comments.article_id
FROM comments
LEFT JOIN articles
ON comments.article_id = articles.id
WHERE articles.id IS NULL;
Relationship Checks
- Missing parent records
- Duplicate primary keys
- Unexpected null foreign keys
- Incorrect cascade rules
- Relationships not enforced by constraints
Relationship Exercise
- Identify a parent and child table.
- Locate their primary and foreign keys.
- Write a query that searches for orphaned records.
- Document the expected relationship.
Character Sets and Collations
Protect multilingual content from encoding problems.
Key Concepts
- Character set defines how text is encoded.
- Collation defines comparison and sorting behaviour.
- Database, table and column settings may differ.
- Application connection settings also affect text.
- Modern multilingual applications commonly use utf8mb4.
Review Table Collation
SELECT
table_name,
table_collation
FROM information_schema.tables
WHERE table_schema = 'your_database'
ORDER BY table_name;
Encoding Exercise
- Record the database default character set.
- Review table collations.
- Find any mismatched tables.
- Test multilingual text in a restored copy.
Reviewing Indexes and Query Performance
Understand how indexes help and when they become unnecessary.
Review Indexes
SHOW INDEX FROM articles;
SHOW INDEX FROM users;
Indexes Commonly Support
- Primary-key lookups
- Foreign-key joins
- Frequently filtered columns
- Frequently sorted columns
- Unique constraints
Index Risks
- Duplicate indexes waste storage.
- Too many indexes slow inserts and updates.
- Indexes on low-value columns may not help.
- Incorrect column order may reduce usefulness.
Index Exercise
- Review indexes on one large table.
- Identify the primary key.
- Identify indexes used for joins or filtering.
- Document any duplicate-looking indexes for further analysis.
Reviewing Slow Queries with EXPLAIN
Understand how the database plans to process a query.
EXPLAIN Example
EXPLAIN
SELECT id, title, created_at
FROM articles
WHERE category_id = 5
ORDER BY created_at DESC
LIMIT 20;
Common Performance Improvements
- Select only required columns.
- Use LIMIT when reviewing a small result set.
- Filter with indexed columns where appropriate.
- Avoid unnecessary wildcard searches.
- Reduce repeated queries inside application loops.
- Review joins and sort operations.
Query Analysis Exercise
- Run EXPLAIN on a SELECT query.
- Record the selected access type and key.
- Remove unnecessary columns.
- Add a reasonable LIMIT.
- Compare the revised execution plan.
Reviewing Database Users and Privileges
Apply least privilege and protect application credentials.
Security Review Checklist
- List database users and allowed hosts.
- Identify unused accounts.
- Review application-user privileges.
- Remove unnecessary administrative rights.
- Rotate exposed or shared passwords.
- Restrict remote access where possible.
- Protect configuration files.
- Avoid storing credentials in public repositories.
Review Grants
SHOW GRANTS FOR 'application_user'@'localhost';
Security Exercise
- List users in a lab database server.
- Review one application's grants.
- Identify privileges that are not required.
- Document a least-privilege replacement plan.
Transactions, Staging and Controlled Changes
Reduce the risk of incomplete or disruptive maintenance.
Transaction Example
START TRANSACTION;
UPDATE users
SET status = 'inactive'
WHERE last_login < '2024-01-01';
SELECT ROW_COUNT() AS affected_rows;
ROLLBACK;
Safe Change Workflow
- Create and test a current backup.
- Reproduce the database in staging.
- Test the SQL change.
- Measure impact and duration.
- Schedule a maintenance window.
- Enable maintenance mode if users may be affected.
- Apply the change.
- Verify the website.
Controlled Change Exercise
- Start a transaction in a lab database.
- Update a small test set.
- Review the affected rows.
- Roll back the change.
- Document the production change plan.
Troubleshooting Connections, Authentication and Imports
Diagnose common website database failures.
| Problem | First Checks |
|---|---|
| Connection refused | Service status, hostname, port, firewall and bind settings |
| Access denied | Username, password, allowed host and privileges |
| Unknown database | Database name, environment and configuration file |
| Import too large | Upload limit, PHP limits and command-line import |
| Import timeout | Execution time, file size, server resources and batch size |
| SQL syntax error | Server version, SQL mode and dump compatibility |
| Broken characters | Character set, collation and connection encoding |
Structured Troubleshooting
- Record the exact error message.
- Confirm the environment and database name.
- Verify the database service is running.
- Check network connectivity and port access.
- Verify credentials and allowed host.
- Review server and application logs.
- Test with a minimal connection.
- Make one controlled change and retest.
Troubleshooting Exercise
- Introduce an incorrect database password in a lab.
- Record the application error.
- Review the database authentication logs.
- Restore the correct credential.
- Verify the website recovers.
Documenting and Scheduling Database Maintenance
Create records, checklists and post-maintenance verification.
Maintenance Record
- Date and time
- Database and server name
- Backup file and location
- Tables reviewed
- SQL statements executed
- Rows affected
- Structural changes
- Issues discovered
- Verification results
- Administrator responsible
Recurring Checklist
- Review backup success.
- Test a restore.
- Record database size.
- Review large and fast-growing tables.
- Inspect errors and slow queries.
- Review users and privileges.
- Clean approved temporary data.
- Verify application functionality.
Post-Maintenance Website Tests
- User sign-in
- Article or product display
- Search
- Forms and transactions
- Administration interface
- Scheduled tasks
- Error logs
Documentation Exercise
- Create a maintenance record template.
- Create a monthly checklist.
- Define post-maintenance website tests.
- Assign owners for backups, review and approval.
Final Project: Complete a Safe Database Maintenance Cycle
Apply the complete inspection, backup, maintenance and verification workflow.
Project Requirements
- Identify the database platform and version.
- Record the database name and size.
- Review table names, engines and collations.
- Identify the five largest tables.
- Create a complete SQL backup.
- Create a compressed copy.
- Restore the backup into a test database.
- Verify table and row counts.
- Check table health.
- Review fragmentation and optimisation candidates.
- Inspect indexes on one large table.
- Use SELECT queries to analyse data.
- Identify duplicate or incomplete records.
- Identify one approved cleanup target.
- Preview affected rows.
- Perform cleanup in staging only.
- Review primary and foreign keys.
- Search for orphaned records.
- Review character sets and collations.
- Run EXPLAIN on one query.
- Review database-user privileges.
- Document all actions.
- Verify application functions.
- Create a recurring checklist.
Recommended Project Workflow
- Inspect
- Back Up
- Restore Test
- Check
- Clean
- Optimise
- Secure
- Verify
Final Verification Checklist
- A current backup exists.
- The backup was successfully restored.
- Table health checks completed.
- No unapproved destructive statement was run.
- Cleanup targets were confirmed before deletion.
- Indexes and slow queries were reviewed.
- Character sets and collations were documented.
- Unused or excessive privileges were identified.
- Website functions were tested.
- Maintenance records were completed.
- A recurring schedule was created.
Congratulations!
You have completed Database Maintenance.
You can now inspect MySQL or MariaDB databases, create and test backups, optimise tables, review indexes, clean approved records, check relationships, secure accounts and troubleshoot common database problems.
Continue protecting website databases through tested backups, staging validation, least-privilege access and recurring health checks.

