Database query languages for efficient queries
One way of looking at database query languages is through the lens of deductive databases, where queries are represented as logic programs. In this setting, the most relevant work related to your question is McAllester's On the complexity analysis of static analyses, which observed that you can reason about the running time of a query by reasoning about the number of "prefix firings" in the rules of your program. What a "prefix firing" is isn't terribly complicated, but I'll refer you to the paper for that.

In the functional programming world, this sort of thing is called a cost semantics: it doesn't mean you can only implement efficient queries (programs), but it means that you can reason about the asymptotic complexity of your declarative program in a reasonable way.

Some later work on implementations of McAllester's ideas include From datalog rules to efficient programs with time and space guarantees (Liu and Stoller) and Dedalus: Datalog in Time and Space (Alvaro, Marczak, Conway, Hellerstein, Maier, and Sears). I admit I haven't yet read the latter of those two papers, however.