It depends on many different things. For the most part, you don't optimize queries. You can optimize the file layout using optimize/binpacking, bloom filters, and zordering but you can't generate stats or influence the query plan.
The idea of "optimizing" has become a bit of a dated way of thinking. Spark has AQE, CBO, and Catalyst do do much of this work for you. Databricks also adds things like disc caching to help too.