Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Consider the following demo.</p> <p>Temporary table for testing:</p> <pre><code>CREATE TEMP TABLE nr(id int, nr numeric); INSERT INTO nr VALUES (1,1),(2,12),(3,13),(4,134),(5,135), (6,136),(7,1362),(8,1363); </code></pre> <p>Query:</p> <pre><code>SELECT nr FROM nr WHERE '1362235' ~~ (nr::text || '%') ORDER BY length(nr::text) DESC LIMIT 1; </code></pre> <p>Delivers the longest match as requested. Operating with strings (not numbers) simplifies the task. You can change the data type in your table or you can cast the values in the query like I did.</p> <p>If you need it to be <strong>fast</strong>, change the type to <code>text</code> and index <code>nr</code>. A search like that can utilize a plain btree index (default) and will be <em>very</em> fast.</p> <pre><code>CREATE INDEX nr_nr_idx ON nr (nr); </code></pre> <p>If your database locale is not 'C' or 'POSIX', use <a href="http://www.postgresql.org/docs/current/interactive/indexes-opclass.html" rel="nofollow"><code>text_pattern_ops</code></a> as @Gavin commented, or the <code>LIKE</code> operator (<code>~~</code>) cannot use it even for the start of the column, because sort order is locale-specific.</p> <pre><code>CREATE INDEX nr_nr_idx ON nr (nr text_pattern_ops); </code></pre> <p>If you need your table column to be a numeric type, there is another option. Use an <a href="http://www.postgresql.org/docs/current/interactive/indexes-expressional.html" rel="nofollow">index on an expression</a> like so:</p> <pre><code>CREATE INDEX nr_nr_idx ON nr ((nr::text) text_pattern_ops); </code></pre> <p>The above query can utilize an index such as this one, because the expression matches the index expression.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload