LoginSignup
1
2

More than 5 years have passed since last update.

PKソートするSELECT文を生成するSQL

Last updated at Posted at 2017-01-19

SQL文

postgreSQL
select
  'select * from ' || tc.table_name || ' order by ' || string_agg(ccu.column_name, ',') || ';' sql 
from
  information_schema.table_constraints tc
  , information_schema.constraint_column_usage ccu 
where
  tc.table_catalog = (データベース名) 
  and tc.table_schema = (スキーマ名) 
  and tc.constraint_type = 'PRIMARY KEY' 
  and tc.table_catalog = ccu.table_catalog 
  and tc.table_schema = ccu.table_schema 
  and tc.table_name = ccu.table_name 
  and tc.constraint_name = ccu.constraint_name 
group by
  tc.table_name

結果

テーブルごとにPKでソートするSQLを生成します。
select * from table1 order by column1, column2;
select * from table2 order by column1, column2;
:
:

1
2
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
1
2