Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i use the like operator in a case select for Postgres SQL?

I would like to write an SQL statement with a CASE WHEN clause that uses the LIKE operator but I am not sure how to properly format the statement.

 SELECT
   services.id,
   (CASE services.description
     WHEN LIKE '%-'
       THEN services.amount * -1
     ELSE services.amount
   END) AS service_amount
 FROM services
like image 378
Peter Black Avatar asked May 04 '17 18:05

Peter Black


People also ask

How do I use like keyword in PostgreSQL?

The PostgreSQL LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. The percent sign represents zero, one, or multiple numbers or characters.

Is like in PostgreSQL case-sensitive?

PostgreSQL is a case-sensitive database by default, but provides various possibilities for performing case-insensitive operations and working with collations.

How do you make a like operator case-insensitive in PostgreSQL?

Use the citext module, which mostly mimics the behavior of a case-insensitive data type. Having loaded that module, you can create a case-insensitive index by CREATE INDEX ON groups (name::citext); .

What is %s in Postgres?

s: It formats the argument value as a string. NULL values are treated as an empty strings. I: It treats the argument value as an SQL identifier. L: It makes the argument value as an SQL literal.


1 Answers

Try it on this way:

SELECT
   services.id,
   CASE WHEN services.description LIKE '%-'
        THEN services.amount * -1
        ELSE services.amount
   END) AS service_amount
 FROM services
like image 188
McNets Avatar answered Sep 30 '22 05:09

McNets