SQLite3: CREATE Table w/ DATE data type, INSERT Rows Using date() Function

Let’s say our UI gives the user a choice between 4 options. They can select option 1, 2, 3 or 4.

You can grab the SQLite Manager Add On for Firefox, use sqlite3 via command line or use commercial software.

The userID can be obtained locally, or in a real life situation, most likely populated from a web service after you log in. The details of how to populate userID are beyond the scope of this note, but are easily searchable online.

Create your TABLE

It’ll consist of these 4 fields:

  • Options ID INTEGER primary key
  • Entry Date INTEGER – stored in YYYY-MM-DD format
  • Choice Type: 1, 2, 3, 4 (1 = option 1, etc) INTEGER
      choice_type INTEGER,
      user_ID INTEGER,

The entry_Date field gets auto populated with today’s date if you fail to provide a value in the INSERT statement.

Save today’s choice

Sample data includes ‘4’ for the chosen option and ‘1823’ as a mock userID. Today’s date is inserted using SQLite’s built-in date() function.

INSERT INTO Choices(choice_type, user_ID, entry_Date) VALUES( 4, 1823, date('now','localtime'))

Save yesterday’s choice

Yesterday’s date is grabbed using SQLite’s built-in date() function plus the NNN days modifier.

INSERT INTO Choices(choice_type, user_ID, entry_Date) VALUES( 1, 1823, date('now','localtime', '-1 days')) 

Get yesterday’s choice

Get the option chosen for YESTERDAY’s date for user ID ‘1823’

SELECT choice_type FROM Choices WHERE Choices.user_ID=1823 AND Choices.entry_Date=date('now','localtime', '-1 days')

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s