Skip to content

Add support for index / query hints in query builder #9119

Open
@joe-meyer

Description

@joe-meyer

I think that we should add support for index hinting in the query builder. I've tried simply adding the hint to the FROM clause, but this tends to break things when doing joins because it tries to add the hint string to those as well (which causes parse errors on the database side.

A couple examples of index hints:
MySQL uses USE INDEX (index_name,index2_name)
MsSQL uses WITH( INDEX(index_name))

I think that this should probably be it's own function on the query builder so that you can easily change the index based on a where clause you might be building or other conditionals. Just spit balling here:

/**
 * @param string|array $indexName 
 * @param null|string $table The table name or alias to apply the index hint to, defaults to first FROM table
 * @return string
 */
function tableHint($indexName, $table = null) {
    ...
}

And could see it being used sort of like this:

public static function queryEmployees($location  = null, $name = null)
{
    $employees = Employee::find();
    if($location !== null) {
        $employees->andWhere(['location' => $location])->tableHint('location_index');
    }


    if($name) {
        $employees->andWhere(['name' => $name])->tableHint('name_index');
    }

    return $employees->all();
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions