Fixed length string comparison in Amazon Redshift


Fixed length string comparison in Amazon Redshift



I have a table in Amazon Redshift called asmt.questions, which has a field called encodedids. This field is varchar and can have comma separated values.
I would like to retreive all the records having any of the following values in them:


Amazon Redshift


asmt.questions


encodedids


varchar


MAT.GEO.107
MAT.GEO.403
MAT.GEO.409.01
MAT.GEO.504.07
MAT.GEO.901.5



To achieve this, I wrote the following query:


SELECT questionid,
encodedids,
irt_a
FROM asmt.questions
WHERE ispublic = TRUE
AND encodedids similar TO '%(MAT.GEO.107|MAT.GEO.403|MAT.GEO.409.01|MAT.GEO.504.07|MAT.GEO.901.5)%'
AND encodedids NOT similar TO '%(MAT.GEO.107.|MAT.GEO.403.|MAT.GEO.409.01.|MAT.GEO.504.07.|MAT.GEO.901.5.)%'
AND irt_a IS NOT NULL
ORDER BY encodedids,
irt_a DESC



This query does a decent job, but it also returns records having values like:


MAT.GEO.10701 (note the added '01' in the end)
MAT.GEO.40301 (note the added '01' in the end)
MAT.GEO.409.0101 (note the added '01' in the end)
MAT.GEO.504.0702 (note the added '02' in the end)
MAT.GEO.901.502 (note the added '02' in the end)



How do I fix the length of the strings to compare so I get only the required values?



Any help would be much appreciated.




1 Answer
1



Storing values in delimited strings is a really bad idea. You should be using a junction table.



Sometimes, we are stuck with other people's really bad decisions. I would probably go for:


where ',' || encodedids || ',' like '%,MAT.GEO.107,%' or
',' || encodedids || ',' like '%,MAT.GEO.403,%' or
',' || encodedids || ',' like '%,MAT.GEO.409.01,%' or
',' || encodedids || ',' like '%,MAT.GEO.504.07,%' or
',' || encodedids || ',' like '%,MAT.GEO.901.5,%'



You can use the same delimiting idea with regular expressions:


where ',' || encodedids || ',' ~ ',MAT.GEO.107,|,MAT.GEO.403,|,MAT.GEO.409.01,|,MAT.GEO.504.07,|,MAT.GEO.901.5,'





Thanks so much! The query works just fine :). I know this may be asking for too much (and I would completely understand if you didn't have the time for this explanation), but I'm not quite sure what ',' || encodedids || ',' ~ is doing in your expression. I would be grateful if you could explain this is simple words :). If not, I completely understand.
– Patthebug
Jun 29 at 18:32


',' || encodedids || ',' ~





The ',' is appending commas to the beginning and end of the expression. The ~ is the POSIX-compliant regular expression matcher in Postgres.
– Gordon Linoff
Jun 30 at 2:54


','


~






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV