1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Oracleでorder by primary keyのSQLを作成するSQL

Posted at

やりたいこと

ディクショナリからテーブルのプライマリキーを取得して↓こんなSELECT文を全テーブル分作成する。

select * from [table_name] order by [pk1], [pk2], ...;

背景

  • 全てのテーブルのレコードを確認する際にselect * from [table_name] order by primary keyがしたかったが、Oracle Databaseではできなさそう
  • プライマリキーでorder byしたselect文を取得するSQLを作成してみる

全テーブルの全レコードをPKでソートして取得するSQL文を作成するSQL

select
    'select * from '||table_name||' order by '||listagg(column_name, ', ') within group (order by table_name) ||';'
from
    ( 
        select
            user_constraints.table_name
            , column_name 
        from
            user_constraints 
            inner join user_cons_columns 
                on user_constraints.constraint_name = user_cons_columns.constraint_name 
        where
            constraint_type = 'P' 
        order by
            user_constraints.table_name
            , position
    ) 
group by
    table_name;

おまけ(上記SQLの途中経過)

全テーブルのPKカラム一覧を取得

select
    user_constraints.table_name
    , column_name
    , position 
from
    user_constraints 
    inner join user_cons_columns 
        on user_constraints.constraint_name = user_cons_columns.constraint_name 
where
    constraint_type = 'P' 
order by
    user_constraints.table_name
    , position;

全テーブルのPKカラム一覧を横持ちで取得

select
    table_name
    , listagg(column_name, ', ') within group (order by table_name) 
from
    ( 
        select
            user_constraints.table_name
            , column_name 
        from
            user_constraints 
            inner join user_cons_columns 
                on user_constraints.constraint_name = user_cons_columns.constraint_name 
        where
            constraint_type = 'P' 
        order by
            user_constraints.table_name
            , position
    ) 
group by
    table_name;
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?