Mar 15, 2017

Sqlite: Using auto_increment and current date and time

The idea

As a good tip to get the most of the table entries - you want the user to focus on their important data - but you don't want to overwhelm them with extra typing that can be done automatically by database system.

Here is way to have an auto increment index and a default date and time of the entry done by the operator

Embedded during the table creation: 

sqlite> create table testauto (autoid integer primary key autoincrement, autodate default (datetime('now')), notes text ) ;

Operator just have to enter the notes column: 

sqlite> insert into testauto (notes) values ('this is a test of the auto increment and default date' ) ;
sqlite> insert into testauto (notes) values ('this is a second test of the auto increment and default date' ) ;
sqlite> insert into testauto (notes) values ('this is a third test of the auto increment and default date' ) ;

and as you see the index and the date are automatically filled

sqlite> select * from testauto ;
1|2017-03-15 15:34:05|this is a test of the auto increment and default date
2|2017-03-15 15:34:14|this is a second test of the auto increment and default date
3|2017-03-15 15:34:24|this is a third test of the auto increment and default date
sqlite>

Feb 10, 2017

Sqlite: how to generate a random number within range 0..99

Random()

The Sqlite random() function will returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807.

abs() will returns the absolute value of the numeric argument

floor() or round() will return a floating-point value X rounded to Y digits to the right of the decimal point. If the Y argument is omitted, it is assumed to be 0.

NB:floor() will only work within SQLExplorer, Dbeaver, ...

Result

select floor(abs(random()/92233720368547758.07));
will generate within 0..99

and
select round(abs(random()/92233720368547758.07),0);
will generate within 1..100

Sqlite: how to count words in a field

Assuming a table like this:

create table test (id integer primary key autoincrement, name text);

and values like:

insert into test values (null, "test") ;
insert into test values (null, "word1 word2 word3")  ;
insert into test values (null, "word4 word5 word6")  ;
insert into test values (null, "word7 word8 word9 word10 word11 word11")  ;

here is the result:

select id, name from test

1;test
2;word1 word2 word3
3;word4 word5 word6
4;word7 word8 word9 word10 word11 word12

Counting

Now you want to count the word(s) in the field "name" - here is how to proceed:
select (length(name)-length(replace(name," ","")))+1 as wordcount, name from test

it works because the query is looking for the number of space - a space means a new word is in the field and that is why you need to add 1 to the total.

Sqlite is awesome

LinkWithin

Related Posts Plugin for WordPress, Blogger...