2

I'm using postgres to pull some data. I have an array (categories) and I want to exclude results that contain ' > '

select title, short_url, unnest(categories) as cats, winning_offer_amount
from auctions
where ended_at is not null
and '% > %' NOT IN cats
group by title, short_url, cats, winning_offer_amount

I realize my syntax is completely wrong but trying to give an idea of what I'm looking to write. A result might be:

Women's > Shoes
Women's
Men's > Shoes
Men's

I would want to exclude results with the ' > '

5
  • You have a text[] called categories that contains things like those four strings and you want to filter out the array entries that contain '>'? So you'd end up with an array like array['Women''s', 'Men''s']? Commented Sep 23, 2014 at 18:53
  • As always, your version of Postgres, please? And do you really want to unnest the array (so you get 1 row for each element), or is this just your attempt to test? Commented Sep 23, 2014 at 20:09
  • Thank you! Postgres 9.3.4 If I don't unnest the results will bunch together everything in the categories array. Commented Sep 23, 2014 at 20:12
  • So do you want the result unnested or not? Commented Sep 23, 2014 at 20:17
  • Sorry, yes I need an unnested result. Commented Sep 23, 2014 at 22:48

2 Answers 2

4

A simple, "brute-force" method would be to cast the array to text and check:

SELECT title, short_url, categories, winning_offer_amount
FROM   auctions
WHERE  ended_at IS NOT NULL
AND    categories::text NOT LIKE '% > %';  -- including blanks?

A clean and elegant solution with unnest() in a NOT EXISTS semi-join:

SELECT title, short_url, categories, winning_offer_amount
FROM   auctions a
WHERE  ended_at IS NOT NULL
AND    NOT EXISTS (
   SELECT 1
   FROM   unnest(a.categories) AS cat
   WHERE  cat LIKE '% > %'
   );

SQL Fiddle.

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

1 Comment

Bingo! Used the first one but unnested categories in the select. Worked like a charm.
0

Count the number of times the '>' character appears in cats and only include the record if the count is equal to zero.

So, something like this (check for exact syntax):

select title, short_url, unnest(categories) as cats, winning_offer_amount
from auctions
where ended_at is not null
and (length(cats) - length(replace(cats, '>', '')))=0 
group by title, short_url, cats, winning_offer_amount

2 Comments

getting error "function length(character varying[]) does not exist"
Can you select unnest(categories) into a temporary table?

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.