Insert missing dates into sqlite result set? - android

I have a table filled with data for given dates. Sometimes I do not have a row for a given day because I might not have data for that day. Now when I query to get the results I would like to have the result set include a row for every date from the earliest date to the latest. Is there a way to form a query that will generate a default row when a date is missing in the results set without actually inserting them in the database? The date column is in the format YYYY-MM-DD.

No matter what the data type, you can create a default value for any column in your table. Please read about the SQL DEFAULT Constraint.
CREATE TABLE Foo (
_id INTEGER PRIMARY KEY,
date TEXT DEFAULT '2012-08-17');
Or if you want to return a default value every time you query your database, use IfNull():
SELECT IfNull(date, '2012-08-17') FROM Foo;
(I have assumed that your date is text, however you can easily change this.)

Related

Sqlite Sort by time not working

I am storing date format in sqlite table, I want sort by date from table.
Every record in my SQLite database contains a column which contains a date stored as a string in the format 'yyyy-MM-dd HH:mm:ss'.
I am sharing my table structure. I am using this query to sort by datetime it not sorting by time but sort by date is working fine.
select *
from messages_table
where id = '444'
order by datetime(date_time) asc
I am storing datetime as string in my below table
and I am getting the below wrong sorting by time output please see my date_time column in the picture, anyone guide me.
I have a similar problem with the TIME datatype.
If I enter time values correctly, such as 8:00 or 13:00, they are sorted as strings in an ORDER BY clause, in effect as "800" and "1300", where the string "1300" is sorted before "800" in ascending order.
One solution is to pad all times with a leading 0, so we get "0800" and "1300" which will be sorted time wise correctly.

How to sort table row based on Specific Column and Month in Android SQLite? [duplicate]

I have an SQLite database within my Android application, which stores dates as integers. These integers are derived from a call to Java.util.Date.getTime();. I am trying to run a raw query of my database to get a Cursor to pass to a CursorAdapter and display in a ListView, but the date is stored as an integer as returned by getTime().
To keep my program simple, I would like to avoid using a SimpleArrayAdapter, and stick with the CursorAdapter.
Is it somehow possible to format the integer within the date colum as mm-dd-yyyy so that the column of the table, that the cursor is pointing to, contains properly formatted values rather than the integer that was returned by Java.util.Date.getTime(); when I added the item to the database?
SELECT strftime("%m-%d-%Y", date_col, 'unixepoch') AS date_col
Your code will work if it expects a result set column in that format called date_col.
EDIT: One thing you need to watch out for is that getTime uses milliseconds since 1970, while standard UNIX time (including SQLite) uses seconds.
The Java.util.Date.getTime(); method is returning an integer that represents the "unix time".
The simplest way to read this number as a date is by storing it as-is, and reading it using the following Sqlite query:
SELECT strftime('%m-%d-%Y', 1092941466, 'unixepoch');
which returns:
08-19-2004
If you need another format, you can use the strftime function to format is as you like, or any of the other date formats and functions available.
You'll have to, as Matthew Flaschen points out in a commend below, divide the date by 1000 before you are able to use them in this way. "Real" unix times are measured in seconds since the epoch, and Java.util.Date.getTime(); returns milliseconds since epoch.
SQLite uses static rigid typing. With static typing, the datatype of a value is determined by its container - the particular column in which the value is stored.
Any value stored in the SQLite database has one of the following storage class:
NULL
INTEGER
REAL
TEXT
BLOB
so I am not sure what you meant by but the date is stored as a long, unhelpful integer.
For more details please refer to Datatypes In SQLite Version 3. For further information on storing date/time in SQLite please refer to SQL As Understood By SQLite.
I hope this helps.

What primary key to use in my SQLite database?

I have a .csv file that I turned into an SQLite database with the first column as a date and time (as a TEXT datatype because it's in the format 7/20/2011 12:00:00 PM), the second column as the subsecond (a REAL, like 0.142857), and the rest of the columns as data about that time. I will be using it as a read-only db in my Android app, in which the user selects a start time and an end time and then the data is displayed graphically for that time period.
This is my first time using a database and I'm not sure how to work with this. I believe I need a unique NUMERIC primary key for each row but simply labeling them by row number is a waste of space. The first column is not unique and is a TEXT datatype anyway, though if the subsecond was to be somehow incorporated then it would be unique. But I really can't re-write the database because it has 65534 rows... How do you suggest I access specific times in this database?
In Android you need a column named _ID in your database (else you'll face some issues later on). You will use that as the primary key.
Dates and times can be stored in SQLite in the form of a text column in the following format (See http://www.sqlite.org/datatype3.html):
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS")
If your database is static, simply use a tool such as SQLite Database Browser to convert it to a format convenient for Android.
If your database is local and external(not remote), than you must have _id and another another table android_metadata which will hold the locale.
If your database was remote. Yes, you can it is only matter of speed if you are write, since you don't. Using WHERE clause will do the work.
Every date can be converted to numeric timestamp quite easy:
Date date = new Date();
long timestamp = date.getTime();
Date otherDate = new Date(timestamp);
Numbers are MUCH easier and faster to process than text fields. If you are completely sure, that you have unique data within column you can use it as primary key.
Importing csv file into table should be also easy:
//just open file in some known way and read it line by line
// we have declared String[] data, String line is line read from your csv somewhere earlier
// in code
data = line.split(",");
//here you have to process values, and execute insert statement
You have to create indexes on every column which will be used to search or order data. Please be also aware, that rows in table has no "default", "natural" or any other order. If you execute this same select statement twice you can get two totally different results in meaning of sorting. So simple select statement should look like that:
select
_id, other_colum_name, some_other_column
from
table_name
where
column_name = 5
and other_column_name = 3
order by
column_name;

How to search a column in an SQLite database for specific text?

More specifically, the first two columns of my read-only database are the row number (the _id integer primary key), and a date and time in the text format 7/21/2011 HH:MM:SS PM. In my Android app, the user selects a start and end time (HH:MM), and then data about that time interval is displayed graphically. How do I search this second row of my database for the inputted times?
So if your Date Column contains TEXT(since there is no DATE in SQLite), you should use the SQLite function
strftime(format, timestring, modifier, modifier, ...)
See docs SQLite Date functions
So you SQL query may look something like this:
SELECT * FROM mytable WHERE strftime('MM-DD-YYYY HH:MM:SS', date_column) < strftime('MM-DD-YYYY HH:MM:SS', '7/21/2010 22:00:00')
where the last date parameter will be the inputted date.
I am not familiar with SQL time commands. If you select all rows and then process them in the java code using Date objects and their .compareTo() methods you can only display rows of interest to your user.

Format integer to formatted date in an SQLite select statement

I have an SQLite database within my Android application, which stores dates as integers. These integers are derived from a call to Java.util.Date.getTime();. I am trying to run a raw query of my database to get a Cursor to pass to a CursorAdapter and display in a ListView, but the date is stored as an integer as returned by getTime().
To keep my program simple, I would like to avoid using a SimpleArrayAdapter, and stick with the CursorAdapter.
Is it somehow possible to format the integer within the date colum as mm-dd-yyyy so that the column of the table, that the cursor is pointing to, contains properly formatted values rather than the integer that was returned by Java.util.Date.getTime(); when I added the item to the database?
SELECT strftime("%m-%d-%Y", date_col, 'unixepoch') AS date_col
Your code will work if it expects a result set column in that format called date_col.
EDIT: One thing you need to watch out for is that getTime uses milliseconds since 1970, while standard UNIX time (including SQLite) uses seconds.
The Java.util.Date.getTime(); method is returning an integer that represents the "unix time".
The simplest way to read this number as a date is by storing it as-is, and reading it using the following Sqlite query:
SELECT strftime('%m-%d-%Y', 1092941466, 'unixepoch');
which returns:
08-19-2004
If you need another format, you can use the strftime function to format is as you like, or any of the other date formats and functions available.
You'll have to, as Matthew Flaschen points out in a commend below, divide the date by 1000 before you are able to use them in this way. "Real" unix times are measured in seconds since the epoch, and Java.util.Date.getTime(); returns milliseconds since epoch.
SQLite uses static rigid typing. With static typing, the datatype of a value is determined by its container - the particular column in which the value is stored.
Any value stored in the SQLite database has one of the following storage class:
NULL
INTEGER
REAL
TEXT
BLOB
so I am not sure what you meant by but the date is stored as a long, unhelpful integer.
For more details please refer to Datatypes In SQLite Version 3. For further information on storing date/time in SQLite please refer to SQL As Understood By SQLite.
I hope this helps.

Categories

Resources