18

I'd like to use UUID as an identifier, provide the first 8 digits to find out if it exists in the database.

normally I can do this without a problem:

select * from TABLE where id = 'e99aec55-9e32-4c84-aed2-4a0251584941'::uuid

but this gives me error:

select * from TABLE where id LIKE 'e99aec55%@'::uuid

error:

ERROR:  invalid input syntax for uuid: "e99aec55%@"
LINE 1: select * from TABLE where id LIKE 'e99aec55...
                                              ^
Query failed
PostgreSQL said: invalid input syntax for uuid: "e99aec55%@"

Is there a way to query first n digits for a UUID type in postgresql?

Zitao Xiong
  • 956
  • 1
  • 10
  • 18

3 Answers3

17

Since you are searching for the highest bits of uuids, you can actually use between (because uuid comparison is well-defined in PostgreSQL):

...
where some_uuid between 'e99aec55-0000-0000-0000-000000000000'
                    and 'e99aec55-ffff-ffff-ffff-ffffffffffff'
pozs
  • 34,608
  • 5
  • 57
  • 63
  • This is cool! I was thinking to create a table with uuid and string of uuid so it uses normal searching. but your methods works very well. Thanks! – Zitao Xiong Nov 05 '15 at 16:59
  • Do you know the performance in Postgresql when using this kind comparison? – Zitao Xiong Nov 05 '15 at 17:06
  • @ZitaoXiong it actually uses a simple btree (should be slightly faster than comparing `text`s, but that depends on a lot of things). – pozs Nov 06 '15 at 09:07
4

UUIDs are not stored as strings in Postrges, they are stored as a 16-byte long binary values. So the only way to query it in the way you want is to convert it to string at first, but the performance of such conversion will be worser than just performing an equality comparison.

Also you will need to maintain an index on those string representation of the UUIDs, so it just doesn't make sense.

Dmitry Sokurenko
  • 6,042
  • 4
  • 32
  • 53
  • make sense, but I'd like to implement something like git's short charcters of SHA in postgresql. something like this: [link](http://stackoverflow.com/questions/18134627/how-much-of-a-git-sha-is-generally-considered-necessary-to-uniquely-identify-a) – Zitao Xiong Nov 05 '15 at 17:05
  • 1
    well then either just store the prefix as an interger / hex encoded string in an another column, or use the solution proposed by pozs. – Dmitry Sokurenko Nov 05 '15 at 17:09
2

Why not just cast your uuid column using id::varchar like so:

select * from TABLE where id::varchar LIKE 'e99aec55%'

Worked for me.

java-addict301
  • 3,220
  • 2
  • 25
  • 37