 
   defp json_library, do: Application.get_env(:ecto, :json_library)
 
-  defp create_names(%{prefix: prefix, sources: sources}, stmt \\ :select) do
+  defp create_names(%{prefix: prefix, sources: sources}, stmt) do
     create_names(prefix, sources, 0, tuple_size(sources), stmt) |> List.to_tuple()
   end
   defp create_names(prefix, sources, pos, limit, stmt) when pos < limit do
     {table, model} = elem(sources, pos)
-    if stmt == :select do
-      id = String.first(table) <> Integer.to_string(pos)
-    else
-      id = quote_id(table)
-    end
+    id = table_identifier(stmt, table, pos)
     [{{prefix, table}, id, model} | create_names(prefix, sources, pos + 1, limit, stmt)]
   end
   defp create_names(_, _, pos, pos, _), do: []
+
+  defp table_identifier(:select, table, pos) do
+    String.first(table) <> Integer.to_string(pos)
+  end
+  defp table_identifier(_stmt, table, _pos), do: quote_id(table)
 
   defp select(%SelectExpr{fields: fields}, distinct, sources) do
     fields = Enum.map_join(fields, ", ", fn (f) ->

  end

  defp order_by(order_bys, sources) do
    exprs = Enum.map_join(order_bys, ", ", fn %QueryExpr{expr: expr} ->
      Enum.map_join(expr, ", ", &ordering_term(&1, sources))
    end)

    if exprs == "" do
      []
    else
      ["ORDER BY", exprs]
    end
  end

  defp ordering_term({:asc, expr}, sources), do: assemble(expr(expr, sources))
  defp ordering_term({:desc, expr}, sources) do

  end

  defp group_by(group_bys, havings, sources) do
    Enum.map_join(group_bys, ", ", fn %QueryExpr{expr: expr} ->
      Enum.map_join(expr, ", ", &assemble(expr(&1, sources)))
    end)
    |> group_by_clause(havings, sources)
  end

  defp group_by_clause("", _, _), do: []
  defp group_by_clause(exprs, havings, sources) do
    ["GROUP BY", exprs, having(havings, sources)]
  end

  defp having([], _sources), do: []
