1

like '%' works as expected for varchar datatype and not works for char datatype in PostgreSQL.

Created a table as below in PostgreSQL: create table movie(movie_name varchar(20), director char(20)); [Note: movie_name is varchar type and director is char type] and inserted few rows using the below query.

insert into movie values('JaiBhim', 'Gnanavel');

insert into movie values('Dharbar', 'ARM');

After this, I used the below select query with '%'.

select * 
from movie 
where movie_name like '%m';

I got correct row details. [JaiBhim and Gnanavel].

I used another select query with '%' as below.

select * 
from movie 
where director like '%M';

For this I expected one row should be returned but it returned 0 rows.

For varchar, 'like %' gives correct result and for char datatype it is not giving.

Is it the expected behaviour?

2
  • 2
    Yes. Read Character types: character(n), char(n) fixed-length, blank padded. The %M is not taking into account the spaces after the M , try %M% or `select * from movie where trim(director) like '%M' Commented Apr 5, 2023 at 16:24
  • 2
    Don't use char Commented Apr 5, 2023 at 17:51

1 Answer 1

0

character pads the values with blanks, so a pattern '%M' will only match a character(10) if the tenth character is an M.

The best solution is to avoid character and use character varying instead, like the documentation recommends. Other than that, you could use a regular expression:

WHERE movie_name ~ 'M *$'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.