0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ナレッジ:業務で使ったSQL

Last updated at Posted at 2025-02-11

PostgreSQLで使ったSQL

table_nameテーブルから全カラムを対象に(*はワイルドカード)where句でカラムの値を絞って上位5件を表示
select *
from table_name 
where column_name1 ='hoge' and column_name2 ='piyo' 
limit 5;
left join
select カラム名
from 外部キーを持つ子テーブル
join 主キーを持つ親テーブル
on  子テーブル.外部キーを持つカラム名 = 親テーブル.主キーであるカラム名
left join 主キーを持つ親テーブル
on 子テーブル.外部キーを持つカラム名 = 親テーブル.主キーであるカラム名
where 条件

select hoge.column_name1,fuga.column_name2,hoge.column_name3,hugahuga.column_name4,hoge.column_name5,piyo.column_name6,hoge.column_name7
from table_name1 as hoge
left join table_name2 as piyo
on hoge.key_column_name = piyo.key_column_name 
and hoge.column_name5 = piyo.column_name5
left join table_name3 as fuga
on hoge.key_column_name = fuga.key_column_name 
and hoge.column_name1 = fuga.column_name1
left table_name4 as hugahuga
on hugahuga.key_column_name = hoge.key_column_name
and hugahuga.column_name1 = hoge.column_name1
and hugahuga.column_name3 = hoge.column_name3
where hoge.key_column_name = 'aaa' and hoge.column_name7 = '11';
実行結果をファイルに出力
\o [出力先ファイル名]
\i [ファイルを読み込んで処理を実行]
\o [出力先ファイルへの書き込み終了]
これでもイケる:実行結果をファイルに出力
\o [出力先ファイル名]
select文実行
\o [出力先ファイルへの書き込み終了]
テーブルの定義とテーブルに含まれるカラムの情報を取得
\d+ table_name
↑の出力例
                                                  テーブル"public.table_name"
                 列                  |           型            | 照合順序 | Null 値を許容 | デフォルト | ストレージ | 統計目標 | 説明
-------------------------------------+-------------------------+----------+---------------+------------+------------+----------+------
 hoge                                | character varying(10)   |          | not null      |            | extended   |          |
 piyo                                | character varying(5)    |          | not null      |            | extended   |          |
 fuga                                | character varying(20)   |          | not null      |            | extended   |          |
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?