3

Can some explain to me why this comparison in postgresql is not working the way I want it to?

So I have a database called customer and it has the columns of customerid, firstname, lastname, phone, and city.. Each one of these columns is a Character(50). I want to find only customers from a certain city and ran multiple queries trying to figure out how to select a certain city.. and I feel like this is going to be a simple answer but I am pretty new to sql querying.

The first query I ran is this

SELECT * 
FROM customer c 
WHERE c.city = 'Denver'

This query returned no results and I also tried LIKE, ILIKE nothing seems to work I've even changed it from character(50) to character varying and still no results.. Not sure what I am doing wrong here

1
  • "If the string to be stored is shorter than the declared length, values of type character will be space-padded [...]" (source). Is there any reason why you chose that particular type? Commented Sep 29, 2016 at 18:41

2 Answers 2

2

Because character pads all values to the defined length. So 'Denver' is stored as 'Denver '

Quote from the manual

Values of type character are physically padded with spaces to the specified width n, and are stored and displayed that way

This is how this data type is defined by the SQL standard. It is an ancient left over.

In a nutshell: never use character. It is always better to use varchar (this is true for essentially every SQL database - and even more so for Postgres).

Sign up to request clarification or add additional context in comments.

Comments

1

You may be able to answer that yourself with a query similar to this:

SELECT FORMAT('''%s''',city) FROM customer WHERE city ILIKE 'D%';

You're looking for the value 'Denver' so I can think of three scenarios:

  1. CHAR(50) has exactly 50 characters all the time every time. Your search for a string with only six characters will properly produce no records. I suggest VARCHAR or VARCHAR(50) for your definition. CHAR is more useful for fixed-length tokens like 2-letter state abbreviations. But you tried a LIKE query so...
  2. Did the wildcard character make it into the LIKE/ILIKE query? Properly, it would look like this: SELECT * FROM customer WHERE city LIKE 'D%';
  3. You didn't mention whether your city column is case-sensitve. If it is, then 'DENVER' is different from 'Denver'. And since you also tried an ILIKE query...
  4. Maybe an obvious first step, and the reason I suggest the query above, is to check that the value actually made it into the table.

Feels like (2) or (4) is the issue.

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.