Maybe it would be good to use some sql parser, http://pyparsing.wikispaces.com/ See: - http://pyparsing.wikispaces.com/file/view/simpleSQL.py - http://pyparsing.wikispaces.com/file/view/select_parser.py