Search code examples
javadatabase-designderby

Best Design for Passing Filter Set into Database Class for SQL use


I'm developing a FlashCard App. Part of this is giving the user the option to filter results on difficulty level and category (more options in the future probably). See the image for a quick mockup of the user screen.

The data for the flash cards are stored in a Derby DB in a single table. One column for Level. A column for each category with a "Y" or "N" holding whether the card falls into that category.

Currently, I have a Filter class that just has a variable for each checkbox. I then pass this to the Database class. But from there it is a complex set of if/else statements to build the correct SELECT statement query.

1) Is there a better way to design this?
2) Is my 1 table approach doomed or is it fine in this case? What pitfalls am I walking into?

Sample Filter
(source: erinchris.com)


Solution

  • The old adage is that in computer science there are three numbers -- zero, one, or infinity. Instead of making a boolean column per level, I would suggest an enum or integer column for level, and either a category table and a JOIN between the two using foreign keys to allow questions to be linked to one or more category, or a "category" column which also uses enums or integers. This way, when you add/remove/rename a new category or level, you are not modifying your database schema. It is independent from the data it contains.


    Also, this will greatly simplify your SQL queries. Compare:

    SELECT * FROM questions WHERE category1 = false AND category2 = false AND category3 = false ... and (level = 1 OR level = 2);
    

    with

    SELECT * FROM questions WHERE category = 1 AND level = 2;
    

    or

    SELECT * FROM questions WHERE category IN (1,3,6) AND level in (1,2);