How does craft deal with Plugin databases when updating plugin versions?
Every time Craft notices that a plugin's version number has changed (I imagine quite near the start of every request,) it checks for any new Database Migrations in that plugin that might need running in order get the database schema caught up to the code. That link, and this one for database queries should be enough to get you started.