Moved index declaration, added some check

Moved index declaration to avoid syntax failure "Key column 'whatever' doesn't exist in table"
And added some checks to avoid failure when nothing in database yet.
Merge pull request #7 from Spir/master

Moved index declaration, added some check