1

I'm trying to get multiple unique rows in a query, the table I'm working with it is:

settings

id category_id key value
1 null phone +2222222222
2 1 phone +1111111111
3 null email [email protected]

So there is a default settings with a null value, and each category can have their own settings, the query that I'm running is:

SELECT MAX(category_id), key, value
FROM settings
WHERE key IN('phone', 'email')
AND (category_id IS NULL OR category_id = 1)
GROUPBY key, value;

But instead return me one value per key, returns both rows.

I want the query return me something like this:

id category_id key value
2 1 phone +1111111111
3 null email [email protected]

if the category_id exists just return that row, not the row with category_id null

3
  • You are grouping by value. Since all three rows have different values in it, the query will produce three rows. Please add the expected result to the question. Commented Oct 21, 2022 at 14:03
  • Ah... seems like the row with 1 has more value than the row with null. Is that correct? Commented Oct 21, 2022 at 14:10
  • yeah, values are differents Commented Oct 21, 2022 at 14:11

1 Answer 1

1

For that you can only GROUP BY key, so you need to add a aggregation function for value, depending on what you want

SELECT MAX(category_id), key, MIN(value)
FROM settings
WHERE key IN('phone', 'email')
AND (category_id IS NULL OR category_id = 1)
GROUP BY key;

max key min
null email [email protected]
1 phone +1111111111
SELECT 2

fiddle

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.