sql commands vol.2

.headers on
.mode column
update users set score = 0, name ='* ' || name where score < 60;
delete from users where score = 0;
select * from users;
&#91;/sql&#93;

transaction
&#91;sql&#93;
begin transaction;
update users set score = score - 10 where name = 'sato';
update users set score = score + 10 where name = 'kimura';
commit;
select * from users;
rollback;
&#91;/sql&#93;

trigger
&#91;sql&#93;
.headers on
.mode column
create table messages (message);

create trigger new_winner update of score on users when new.score > 100
  begin
   insert into messages (message) values (
     'name: ' || new name ||
     ' ' || old. score ||
     ' ->' || new.score
   );
   end;

update users set score = score + 30;
select * from messages;

index

create index score_index on users(score);
create unique index name_index on users(name);

.indices users
.schema users

drop index if exists score_index;
drop index if exists name_index;

日時

select datetime('now', '+09:00:00');
select date('2016-12-01', '+3 months', 'start of month', '-1 day');

create table if not exists users (
  id integer primary key,
  name varchar(255) not null,
  score integer default 10 check(score >= 0),
  team text,
  created datetime default (datetime('now', '+09:00:00'))
);

複数テーブルの作成

drop table if exists posts;
create table if not exists posts (
  id integer primary key,
  title text,
  body text,
  created datetime default (datetime('now', '+09:00:00'))
);

insert into posts (id, title, body) values (1, 't1', 'b1');
insert into posts (id, title, body) values (2, 't2', 'b2');

drop table if exists comments;
create table if not exists comments (
    id integer primary key,
    post_id integer,
    comment text,
    created datetime default (datetime('now', '+09:00:00'))
  );
  insert into comments (id, post_id, comment) values (1, 1, 'c1');
  insert into comments (id, post_id, comment) values (2, 1, 'c2');

.headers on
.mode column

select * from posts;
select * from comments;

内部結合 inner join、外部結合 left outer join、交差結合 cross join

select * from posts inner join comments on posts.id = comments.post_id;
select * from posts join comments on posts.id = comments.post_id;
select posts.id, posts.title, comment from posts join comments on posts.id = comments.post_id;
select * from posts left outer join comments on posts.id = comments.post_id;
select * from posts cross join comments;

row id ※integer primary key -> row id

select rowid, * from users;

dump

.output users.dump.sql
.dump users

外部データの取り込み

drop table if exists users;
create table users (
  id integer primary key,
  name,
  score
);
insert into users (name, score) values ('a', 10);
insert into users (name, score) values ('b', 20);
insert into users (name, score) values ('c', 30);

create table temp(name, score);

.mode csv
.import users.csv temp

insert into users(name, score) select name, score from temp;
select * from users;

drop table temp;

.mode csv
.output users_out.csv
select * from users;