Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use LIKE on inet field in Postgres

I need to perform the following query:

SELECT * FROM users WHERE ip LIKE '88.99.%';

The problem is that the inet datatype does not seems to support wildcards (at least not in the way I have utilized them in the preceding query).

What I'd like to know is whether it would be a smart move to convert the field into string before specifying the LIKE filter? (On the other hand, this would probably slow down the whole query, even if the approach itself was valid.)

like image 676
Aley Avatar asked Apr 24 '13 11:04

Aley


People also ask

What is the use of like clause in PostgreSQL?

The PostgreSQL LIKE is used in matching text values against patterns using wildcards. The LIKE clause allows us to use wildcards in SELECT, UPDATE, INSERT, or DELETE statements.

How to use wildcards in PostgreSQL like clause?

Step 1) Type the following query in the query editor: Step 2) Click the Execute button. It should return the following: The PostgreSQL LIKE is used in matching text values against patterns using wildcards. The LIKE clause allows us to use wildcards in SELECT, UPDATE, INSERT, or DELETE statements.

Does PostgreSQL support regular expressions matching?

PostgreSQL supports regular expressions matching. SELECT * FROM books WHERE title ~ '^\d+ ?' Show activity on this post. Show activity on this post.

Can the like and equals symbols be combined?

These symbols can also be combined. If the LIKE operator is not used together with these two signs, it will act like the equals operator. Here is the syntax for the LIKE operator: The expression is a character expression like a column or field. The pattern is a character expression with pattern matching.


2 Answers

Use subnet operators for such queries. '88.99.0.0/16' should do it :

SELECT * FROM users WHERE ip << inet '88.99.0.0/16';
like image 183
Jakub Kania Avatar answered Oct 18 '22 23:10

Jakub Kania


Another option which worked for me if you want to do a string comparison is this:

SELECT * FROM users WHERE TEXT(ip) LIKE '88.99.%';

although it will be less efficient than "How to use LIKE on inet field in Postgres".

Reference: https://www.postgresql.org/docs/8.2/static/functions-net.html

like image 12
Tom Jenkinson Avatar answered Oct 18 '22 23:10

Tom Jenkinson