'Response Slow when Order BY is added to my SQL Query

I have the following job_requests table schema as shown here

+-------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id             | int(11)      | NO   | PRI | NULL    | auto_increment |
| available_to.  | integer[]    | NO   |     |         |                |
| available_type | varchar(255) | NO   |     | NULL    |                |
| start_at       | varchar(255) | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

I have the following query to return a list of records and order them by the type_of_pool value

WITH matching_jobs AS (
        SELECT
            job_requests_with_distance.*,
            CASE WHEN (users.id = ANY (available_to) AND available_type = 0) THEN 'favourite'
            ELSE 'normal'
            END AS type_of_pool
        FROM (
            SELECT
                job_requests.*,
                users.id AS user_id,
    
            FROM
                job_requests,
                users) AS job_requests_with_distance
        LEFT JOIN users ON users.id = user_id
    WHERE start_at > NOW() at time zone 'Asia/Kuala_Lumpur'
        AND user_id = 491
        AND (user_id != ALL(coalesce(unavailable_to, array[]::int[])))
    )
    
    
    SELECT
        *
    FROM
        matching_jobs
    WHERE (type_of_pool != 'normal')::BOOLEAN
    ORDER BY
      array_position (ARRAY['favourite','exclusive','normal']::text[], type_of_pool),
    LIMIT 30

If i remove the ORDER BY function, it takes about 3ms but when I add the ORDER BY function, it takes about 1.3seconds to run.

Not sure how do i optimize this query to make it faster? I have read using Indexes and all but not sure how an index will help in this scenario.

Any help is appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source