SQL indexing on varchar

前端 未结 5 839
伪装坚强ぢ
伪装坚强ぢ 2020-12-25 15:32

I have a table whose columns are varchar(50) and a float. I need to (very quickly) look get the float associated with a given string. Even with ind

5条回答
  •  醉梦人生
    2020-12-25 16:04

    I'd recommend simply a hash index:

    create index mytable_phrase_idx on mytable using hash(phrase);
    

    This way queries like

    select floatval from mytable where phrase='foo bar';
    

    will be very quick. Test this:

    create temporary table test ( k varchar(50), v float);
    insert into test (k, v) select 'foo bar number '||generate_series(1,1000000), 1;
    create index test_k_idx on test using hash (k);
    analyze test;
    explain analyze select v from test where k='foo bar number 634652';
    
                                                       QUERY PLAN                                                    
    -----------------------------------------------------------------------------------------------------------------
     Index Scan using test_k_idx on test  (cost=0.00..8.45 rows=1 width=8) (actual time=0.201..0.206 rows=1 loops=1)
       Index Cond: ((k)::text = 'foo bar number 634652'::text)
     Total runtime: 0.265 ms
    (3 rows)
    

提交回复
热议问题