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.