SQLの基礎(3)まずは一つ一つ納得するより、感覚的に慣れるようにします
日付処理
- DB(PostgreSQL)と接続する
$ psql -U postgres
- テーブル内容を確認する
postgres=# select * from cal;
- 範囲指定して抽出する
postgres=# select dt from cal where dt between '20220810' and '20220820';
- 月曜日を指定して抽出する
postgres=# select dt from cal where to_char(dt,'TMDy')='月';
- 90日後の日付を取得する
postgres=# select dt as 日付, dt + integer '90' as 90日後 from cal;
- DB(PostgreSQL)を切断する
postgres=# \q
データ抽出範囲
- DB(PostgreSQL)と接続する
$ psql -U postgres
- 10件のみを抽出する
postgres=# select * from cal order by dt limit 10;
- 5件目から抽出する
postgres=# select * from cal order by dt offset 5;
- 5件目から10件のみを抽出する
postgres=# select * from cal order by dt limit 10 offset 5;
- DB(PostgreSQL)を切断する
postgres=# \q
データ登録制約(未入力禁止)
- DB(PostgreSQL)と接続する
$ psql -U postgres
- テーブル作成する
postgres=# create table msg( id int, msg text, dt date NOT NULL );
- データを登録する
postgres=# insert into msg(id,msg,dt) values(99,'こんにちは','now');
postgres=# insert into msg(msg,dt) values('こんにちは','now');
postgres=# insert into msg(id,dt) values(99,'now');
postgres=# insert into msg(id,msg) values(99,'こんにちは');
postgres=# insert into msg(id) values(99);
postgres=# insert into msg(msg) values('こんにちは');
postgres=# insert into msg(dt) values('now');
- 登録データを確認する
postgres=# select * from msg;
- テーブルを削除する
postgres=# drop table msg;
- DB(PostgreSQL)を切断する
postgres=# \q
データ登録制約(同値禁止)
- DB(PostgreSQL)と接続する
$ psql -U postgres
- テーブル作成する
postgres=# create table msg( id int UNIQUE, msg text, dt date );
- データを登録する
postgres=# insert into msg(id,msg,dt) values(99,'こんにちは','now');
postgres=# insert into msg(msg,dt) values('こんにちは','now');
postgres=# insert into msg(id,dt) values(99,'now');
postgres=# insert into msg(id,msg) values(99,'こんにちは');
postgres=# insert into msg(id) values(99);
postgres=# insert into msg(msg) values('こんにちは');
postgres=# insert into msg(dt) values('now');
- 登録データを確認する
postgres=# select * from msg;
- テーブルを削除する
postgres=# drop table msg;
- DB(PostgreSQL)を切断する
postgres=# \q
|