SQL 基本構文

1 行の挿入(insert)

基本構文

insert into テーブル
values('項目1','項目2'…)

(例1)

insert into 家計簿
values('2020-02-12','運搬費','タクシー','0','2000')

(例2:現在の日付を得る{CURRENT_DATE})

insert into 家計簿
values(CURRENT_DATE,'運搬費','タクシー','0','2000')

2 行の更新(update)

基本構文

update テーブル名
Set 項目 = '更新値'
Where 項目 ='条件値' ★このWhereがないとヤバい(全部同じ値で更新される)

(例)

update 家計簿
set メモ = 'トラック'
where 費目 = '運搬費'

(例2:2つの条件式を組み合わせたWhere句)

update 家計簿
set メモ = 'リムジン'
where 費目 ='運搬費' and 出金額 > 2000

(例3:文字の一部を置換する。費 → 代)

update 家計簿
set 費目 = replace(費目,'費','代')

3 行の削除(delete)

基本構文

delete from テーブル名
where 項目 ='条件値'

(例)

delete from 家計簿
where メモ = 'タクシー'

4 行の選択(Select)

基本構文

Select 項目 from テーブル名

(例1:テーブルのデータをすべて抽出)

Select * from 家計簿

(例2:以上、以下)

select * from 家計簿
where 出金額 > 3000 

(例3:NULL値を取得) ★NULLは'=(イコール)'では判定できない。

select * from 家計簿
where 費目 is null


★Nullで無い場合(is not Null)
select * from 家計簿
where 費目 is not null

(例4:パターンマッチング{項目メモに、文字列に"入"が入っている行})

select * from 家計簿
where メモ like '%入%'

例)4-2:パターンマッチング(1の後に5文字はいいている行)

select * from 家計簿
where メモ like '1_____'
  
エスケープ句 「Escape '$'」あり。

例)4-3:BETWEEN A AND B(A以上B未満)

select * from 家計簿
where 出金額 between 1000 and 3000   ★(1000円以上、3000以下)

例)4-4:in(複数値との比較)

select * from 家計簿
where 費目 in('食費','給料')
  
★not in
select * from 家計簿
where 費目 not in('食費','給料')

例)4-5:2つの条件を組み合わせたWhere句(and)

select * from 家計簿
where 費目 ='運搬費' and 出金額 >= 2000

SELECT文だけに可能な修飾

DISTINCT :重複行を除外
ORDER BY :検索結果の順序を並び替える
LIMIT  :検索結果の件数を限定して取得する。★SQL非標準。SQL ServerではTOP
UNION  :検索結果にほかの検索結果を足し合わせる
EXCEPT  :検索結果からほかの検索結果を差し引く
INTERSECT:検索結果とほかの検索結果で重複する部分を取得する

1)DISTINCT :重複行を除外
2)ORDER BY :検索結果の順序を並び替える

select * from 家計簿
order by 日付 desc  ★並び順の省略はASC(昇順)になる。descは

  
★複数列の並べ替え★
select * from 家計簿
order by 日付 asc ,出金額 desc

  
★列名でも指定可能★
select * from 家計簿
order by 1 asc ,5 desc

3)先頭から数件だけ取得(Limit)

select * from 家計簿
order by 5 desc Limit 2

*この場合2件


★先頭から3番目に高い出金額を取得する(Limit 1 OFFSET 2)★
select * from 家計簿
order by 5 desc Limit 1 offset 2
  

4)UNION:検索結果にほかの検索結果を足し合わせる

5 テーブルの作成(create table)

create table 家計簿2(
 日付 date,
 費目ID integer
)


create table 家計簿3(
 日付 date,
 費目ID integer,
 メモ varchar(100) default '不明'
)



6 テーブルの削除(Drop table)

基本構文

Drop table テーブル名

(例)

Drop table 家計簿2

7 テーブルの結合(join)

基本構文

select 選択列リスト from テーブルA
JOIN テーブルB
on 両テーブルの結合条件

(例1:2つのテーブルを結合)

select 家計簿.費目,家計簿集計.費目,家計簿集計.平均 from 家計簿
join 家計簿集計
on 家計簿.費目 = 家計簿集計.費目

8 副問い合わせ

Selectをネストする。

1つのSQL文で第歳の出費に関する費目と金額を求める。

select 費目,出金額 from 家計簿
where 出金額 = (SELECT max(出金額) from 家計簿)