PostgreSQL
 SQL >> Datenbank >  >> RDS >> PostgreSQL

Je nach Eingabe zwischen indexierter und nicht indexierter Abfrage wechseln

In reinem SQL ist das meines Erachtens nicht machbar. Nach PL/pgSQL lässt es sich aber problemlos übersetzen:

CREATE OR REPLACE FUNCTION public.usp_get_data(
    i_distance_choice integer,
    i_longitude double precision,
    i_latitude double precision)
  RETURNS TABLE(convo_id bigint)
  LANGUAGE plpgsql STABLE AS
$function$
BEGIN
  IF i_distance_choice < 75 THEN
    RETURN QUERY
      SELECT po.convo_id
      FROM post po
      WHERE ST_DWithin(po.geog,
                       ST_SetSRID(ST_MakePoint(i_longitude, i_latitude), 4326),
                       i_distance_choice * 1609.34)
      ORDER BY po.reply_count DESC, convo_id DESC
      LIMIT 10;
  ELSE
    RETURN QUERY
      SELECT po.convo_id
      FROM post po
      WHERE po.geog <-> ST_SetSRID(ST_MakePoint(i_longitude, i_latitude), 4326)
            < i_distance_choice * 1609.34
      ORDER BY po.reply_count DESC, convo_id DESC
      LIMIT 10;
  END IF;
END
$function$

Ich habe geprüft: Unterhalb von 75 wird der Geography-Index genutzt, ab 75 der Btree-Index (reply_count, convo_id).