I have a table with three columns `time_stamp`, `device_id` and `status` s.t `status` type is `json`. Also `time_stamp` and `device_id` columns have *index*. I need to grab latest value of status with id `1.3.6.1.4.1.34094.1.1.1.1.1` which is not null.

You can find query execution time of following command **With** and **Without** using **MAX** bellow.

Query with MAX:

```
SELECT DISTINCT MAX(time_stamp) FROM device.status_events WHERE 
(device_id = 7) AND
   (status->'1.3.6.1.4.1.34094.1.1.1.1.1' != '{}');

```

[![query with MAX](https://i.stack.imgur.com/CHvuM.png)](https://i.stack.imgur.com/CHvuM.png)

Query without MAX:

```
SELECT DISTINCT time_stamp FROM device.status_events WHERE 
(device_id = 7) AND
   (status->'1.3.6.1.4.1.34094.1.1.1.1.1' != '{}');

```

[![query without MAX](https://i.stack.imgur.com/YtzyZ.png)](https://i.stack.imgur.com/YtzyZ.png)

First query takes about **3sec** and second one takes just **3msec** with two different plans. I think both queries should have same query plan, Why it does not use *index* in when it wants to calculate MAX? How can improve running time of first query?

**PS** I use postgres 9.6(dockerized version).

Also this is table definition.

```
-- Table: device.status_events

-- DROP TABLE device.status_events;

CREATE TABLE device.status_events
(
  time_stamp timestamp with time zone NOT NULL,
  device_id bigint,
  status jsonb,
  is_active boolean DEFAULT true,
  CONSTRAINT status_events_device_id_fkey FOREIGN KEY (device_id)
      REFERENCES device.devices (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)
WITH (
  OIDS=FALSE
);
ALTER TABLE device.status_events
  OWNER TO monitoring;

-- Index: device.status_events__time_stamp

-- DROP INDEX device.status_events__time_stamp;

CREATE INDEX status_events__time_stamp
  ON device.status_events
  USING btree
  (time_stamp);

```