1

I'm new to PostgreSQL. I am currently working on a 3rd party PostgreSQL database, and I have limited READ permissions, so I'm unable to create a temp table, or create "user defined" variables. Moreover, I found that dealing with regular expressions is more difficult in Postgres than MySQL.

Question:
I have the following dummy table:

Code   |  Name
11199  |  a
22299  |  b
33399  |  c
44499  |  a
55599  |  c

Now I have an offline list (can't create/modify tables in this DB) of numbers. I need to select the names whose code starts with these numbers - but the return code should be the code in the query statement.

Example list of numbers:

1
2
3
4
5

Desired query result:

code  |   name
1     |   a
2     |   b
3     |   c
4     |   a
5     |   c

I could think of ways to accomplish it if I had more db permissions (such as inserting the list to a table in the database, plus using temp tables + if I could use regex like in mysql), but I don't know where to start on Postgres with this. Help? :)

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Rani
  • 649
  • 2
  • 7
  • 9

2 Answers2

3

something like this:

-- using cte as your list of numbers
with cte as (
   select unnest(array[1, 2, 3, 4, 5]) as Number
)
select c.Number, t.name
from Table1 as t
    inner join cte as c on t.code::text like c.Number::text || '%'

sql fiddle demo

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
0

Revisit your assumptions. Regular expressions are a basic, standard feature in Postgres. There are also a number of built-in functions using regex.

But you don't need a regular expression here. Use the standard SQL LIKE operator. See:

You can provide the list as array and unnest() as demonstrated by Roman or directly with an ad-hoc table using a VALUES expression. I am assuming, that multiple rows can match and you only want a single result per number in your list:

SELECT n.nr, array_agg(t.name) AS names
FROM  (VALUES (1), (2), (3), (4), (5)) n(nr)
JOIN   tbl t ON t.code LIKE (n.nr || '%')
GROUP  BY 1;

Advanced solutions for big list

If you have a (big) file holding numbers (and the necessary privileges!), you could utilize more advanced techniques like:

  • COPY to a temp table
  • pg_read_file() (for special purposes, needs superuser privileges)
  • A foreign data wrapper on the file (file_fdw)

Related:

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228