Rojo
Rojo

Reputation: 276

SQL design: finding rows that are not on a different table

Simplified situation: I have a table, let's call it header with, say, a primary key header_ID, and some other attributes

I will be needing to flag those rows with different filters. I can't know in advance how many, but for most rows it will be between 0 to 10.

So, I thought of creating another table (let's call it filter) with attributes h_ID and filter_ID. So, if this table has the following it would mean that header_ID=2 was flagged with the filter 1 and 3, and header_ID=3 with filter 1

2 1 2 3 3 1

Then, another table with filter_ID and an attribute with some text describing the filter.

The basic query that I see myself doing often is, for example, "get certain rows from header that don't have any filters". Is this a design that makes these types of queries efficient? If so, how?

I was thinking about perhaps adding a filter_ID column to header, and replacing header_ID column with a filter_ID primary key, that will have value NULL in header when no filters have been assigned. Is that a better idea?

I appreciate your input

Upvotes: 0

Views: 45

Answers (1)

invertedSpear
invertedSpear

Reputation: 11054

You can do a left join and then filter to only get rows with null values in the left table.

SELECT [cols]
FROM header
LEFT JOIN filters 
ON header_id=h_id
WHERE [filter col] IS NULL

By the descriptions of your tables, it would be a pretty bad idea to have a filter column in the header table. It would lead to some pretty inefficient queries.

Upvotes: 1

Related Questions