Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres SELECT where the WHERE is UUID or string

Tags:

postgresql

I have the following simplified table in Postgres:

  • User Model
    • id (UUID)
    • uid (varchar)
    • name (varchar)

I would like a query that can find the user on either its UUID id or its text uid.

SELECT * FROM user WHERE id = 'jsdfhiureeirh' or uid = 'jsdfhiureeirh'; 

My query generates an invalid input syntax for uuid since I'm obviously not using a UUID in this instance.

How do I polish this query or check if the value is a valid UUID?

like image 786
Wainage Avatar asked Sep 26 '17 18:09

Wainage


People also ask

How is UUID stored in Postgres?

PostgreSQL allows you store and compare UUID values but it does not include functions for generating the UUID values in its core. Instead, it relies on the third-party modules that provide specific algorithms to generate UUIDs.

What is UUID-OSSP?

The uuid-ossp module provides functions to generate universally unique identifiers (UUIDs) using one of several standard algorithms. There are also functions to produce certain special UUID constants. This module is only necessary for special requirements beyond what is available in core PostgreSQL.

Is UUID good for primary key Postgres?

Numbers generated by a sequence and UUID s are both useful as auto-generated primary keys. Use identity columns unless you need to generate primary keys outside a single database, and make sure all your primary key columns are of type bigint .

How do I do a wildcard search in PostgreSQL?

Use ILIKE : SELECT * FROM table WHERE columnName ILIKE 'R%'; or a case-insensitive regular expression: SELECT * FROM table WHERE columnName ~* '^R.


1 Answers

Found it! Casting the UUID column to ::text stops the error. Not sure about the performance hit but on about 5000 rows I get more than adequate performance.

SELECT * FROM user WHERE id::text = 'jsdfhiureeirh' OR uid = 'jsdfhiureeirh';  SELECT * FROM user WHERE id::text = '33bb9554-c616-42e6-a9c6-88d3bba4221c'    OR uid = '33bb9554-c616-42e6-a9c6-88d3bba4221c'; 
like image 192
Wainage Avatar answered Oct 01 '22 13:10

Wainage