JR中央線・三鷹駅
南口 徒歩3分

[ 地図 ]
TOP 学習環境 SQL C言語 Java

 SQLの基礎(3)
    まずは一つ一つ納得するより、感覚的に慣れるようにします
日付処理
  1. DB(PostgreSQL)と接続する
  2. $ psql -U postgres

  3. テーブル内容を確認する
  4. postgres=# select * from cal;

  5. 範囲指定して抽出する
  6. postgres=# select dt from cal where dt between '20220810' and '20220820';

  7. 月曜日を指定して抽出する
  8. postgres=# select dt from cal where to_char(dt,'TMDy')='月';

  9. 90日後の日付を取得する
  10. postgres=# select dt as 日付, dt + integer '90' as 90日後 from cal;

  11. DB(PostgreSQL)を切断する
  12. postgres=# \q
データ抽出範囲
  1. DB(PostgreSQL)と接続する
  2. $ psql -U postgres

  3. 10件のみを抽出する
  4. postgres=# select * from cal order by dt limit 10;

  5. 5件目から抽出する
  6. postgres=# select * from cal order by dt offset 5;

  7. 5件目から10件のみを抽出する
  8. postgres=# select * from cal order by dt limit 10 offset 5;

  9. DB(PostgreSQL)を切断する
  10. postgres=# \q
データ登録制約(未入力禁止)
  1. DB(PostgreSQL)と接続する
  2. $ psql -U postgres

  3. テーブル作成する
  4. postgres=# create table msg( id int, msg text, dt date NOT NULL );

  5. データを登録する
  6. 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');

  7. 登録データを確認する
  8. postgres=# select * from msg;

  9. テーブルを削除する
  10. postgres=# drop table msg;

  11. DB(PostgreSQL)を切断する
  12. postgres=# \q
データ登録制約(同値禁止)
  1. DB(PostgreSQL)と接続する
  2. $ psql -U postgres

  3. テーブル作成する
  4. postgres=# create table msg( id int UNIQUE, msg text, dt date );

  5. データを登録する
  6. 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');

  7. 登録データを確認する
  8. postgres=# select * from msg;

  9. テーブルを削除する
  10. postgres=# drop table msg;

  11. DB(PostgreSQL)を切断する
  12. postgres=# \q
SQL(1) SQL(2) SQL(3) SQL(4) SQL(5)
Copyright© Ciapia IT Academy 2022.