Skip to the content.

データベース

用語

CRUD

構成

以下のようにデータベースは3段構造になっていることが基本

クエリ

-- ソート昇順
select * from テーブル名 order by カラム名 asc;
-- ソート降順
select * from テーブル名 order by カラム名 desc;
-- 時刻指定
select * from テーブル名 where created_at >= '20240101 050000'::TIMESTAMP limit 100;

-- テーブルのカラム名を横並びで取得する
select group_concat(カラム名 separator ', ') as columns from information_schema.columns where table_schema = 'DB名' and table_name = 'テーブル名' order by ordinal_position asc;

-- データをグループ化する
select カラム名1, カラム名2 from テーブル名 group by カラム名1;

-- データをグループ化し、条件抽出する
select カラム名1, カラム名2 from テーブル名 group by カラム名1 having カラム名>1;

-- 複数の対象のどれかに該当する値を取得
select * from テーブル名 where カラム名 in(1,2,3);

-- テーブルのカラム数を取得
select count(カラム名) from information_schema.columns where table_name='テーブル名' and table_schema='DB名';

-- 外部キー確認
select * from information_schema.key_column_usage where table_schema='DB名' and table_name='テーブル名';
update TABLE_NAME set COLUMN_NAME1='AAA', COLUMN_NAME2='BBB',updated_at=now() where id=999;
delete from TABLE_NAME; -- テーブルを削除する
insert into words (english, japanese,created_at,updated_at) values 
('availability','可用性',now(),now()),
('arn','Amazon リソースネーム (ARN)',now(),now());
-- 指定テーブル削除
drop table テーブル名;
-- 依存テーブルも含めて指定テーブルを削除
drop table テーブル名 cascade;
-- 型変更
ALTER TABLE テーブル名 ALTER COLUMN カラム名 TYPE タイプ;

-- カラム追加
ALTER TABLE テーブル名 ADD COLUMN カラム名 TYPE タイプ;
begin;
update table_name set column_name1=1, column_name2='test' where id=999;
rollback; -- 戻す
commit;

SQL構文ルール

下に行くほど優先度が下がる(上ほど処理の優先度が高い)

機能 構文
テーブルの指定 FROM
結合 ON / JOIN
取得条件 WHERE
グループ化 GROUP BY
関数 COUNT / SUM / AVG / MIN
取得条件 HAVING
検索 SELECT / DISTINCT
順序 ORDER BY
LIMIT LIMIT