You should trim data as it comes into your application (from a submitted form), rather than just before you put it into the database. It's a validation step to get data into a controlled format, rather than an escaping step to store in a database safely. (*)
You should also be doing removal of control characters and anything else that will cause your application trouble at this point. For example, imagine the difficulty (and potential security problems) a username with a newline character or null byte in it could cause. A typical browser UI might not allow those characters to be typed, but that doesn't stop an attacker submitting them. Some form-reading libraries may take care of this for you, most won't.
Not everything needs trimming. For example big text fields like the one I'm typing in now might have a valid reason to have whitespace at the start and/or end. But it's worth doing for anything that has logic associated with it, most notably things like usernames.
*: there is one database issue with untrimmed spaces: many databases will silently trim trailing spaces, and unexpectedly match strings with any number of trailing spaces. Don't expect to get trailing spaces back from the database unless it's a BLOB column, and again, trim before doing anything with logic like matching usernames.