SQL databases work by compiling SQL statements into programs that are executed by a virtual machine. The virtual machine consists of several key components, including a parser, code generator, virtual machine, B-tree storage structure, pager, and OS interface. Indexes play an important role in allowing the query optimizer to select the most efficient execution plan for a given SQL statement. The optimizer aims to minimize the cost of executing the statement in terms of memory, disk I/O, and processing time.