Search code examples
javaandroidsqlitedatetimeandroid-sqlite

SQLite filter records by part of column value


Background:

Following are the tables that I have:

Persons table:

Id      Name
-------------

1       user1
2       user2

Orders table:

Id      Name        Date                        YearMonth       UserId
----------------------------------------------------------------------

1       item1       2015-11-01 02:34:46         2015-11         2
2       item2       2018-09-06 01:04:16         2018-09         1
3       item3       2018-09-23 04:44:21         2018-09         1
4       item4       2018-09-02 11:10:08         2018-09         2
5       item5       2019-11-01 02:54:02         2019-11         1

On the UI side I have defined a spinner for each user which is populated with YearMonth column of orders table. For example for user1 the spinner would be populated with:

  • 2019-11
  • 2018-09

I use this query to populate the spinner:

 Cursor cursor = db.query("orders",new String[] {"YearMonth"}, "UserId = "+id,
            null, "YearMonth", null, "YearMonth DESC");

// id is a local variable which stores the id of a particular user  

And whenever I select any of the YearMonth from the spinner all the orders brought on that year and month get returned with this query:

Cursor cursor = db.query("orders",null,"UserId = ? and YearMonth = ?",
            new String[] {id+"", selectedYearMonth}, null, null, null);

// selectedYearMonth is the value of spinner which is currently selected.

Problem:

If you notice carefully the column YearMonth in orders table is unnecessary I could have done the same with just date column which also mentions the year and month of orders and this is where I want your help.

Can you show me a right way with which I can filter the above queries with part of date column without the need of defining the unnecessary YearMonth column for just filtering the records ?


Solution

  • Modified the solution of @forpas to best suite the Question:

    Modified query for Spinner:

    Cursor cursor = db.query("orders", new String[] {"SUBSTR(orderDate, 1, 7) YearMonth"},
                            "userId = ?", new String[] {String.valueOf(personId)},
                            "YearMonth", null, "YearMonth DESC");    
    

    Modified query of getting orders:

    Cursor cursor = db.query("orders",null,"userId = ? and SUBSTR(orderDate, 1, 7) = ?",
                             new String[] {personId+"", item}, null, null, null);