PostgreSQLパフォーマンスチューニング(重いSQLを見つける方法)

PostgreSQLパフォーマンスチューニング(重いSQLの見つけ方)メモ。

参考url:
http://blog.asial.co.jp/383

ログファイルを見ながらSQLを実行して 重いSQLを発見する方法が書かれています。
インデックス(index)の重要性が良く分かります。

一箇所でも重い部分があると、全体のパフォーマンスに大きく影響するそうなので、
パフォーマンスが出ないなあと感じたら見直してみましょう。

PostgreSQLのバックアップとリストア方法

PostgreSQLのデータベースをまるごとバックアップとリストア備忘録。

まずは、バックアップから。
今回はpg_dumpのカスタムアーカイブを使います。

$ su - postgres

-bash-3.00$ pg_dump -U postgres -F c -f 2008-03-14-backup.car sampledb

-bash-3.00$ pg_restore -U postgres -d new_sampledb -F c 2008-03-14-backup.car

PostgreSQLで外部結合した時、NULL値を初期値に変換する方法

「OUTER JOIN」等、外部結合の時のNULL値を他のデフォルト値に置き換える方法。RDBMSはPostgreSQL。

参考サイト:SQL の COALESCE
http://sonic64.com/2003-07-29.html

COALESCE()という関数を使えば良いみたい!

SELECT  t1.name,
        COALESCE(v1.quantity, 0)   AS quantity
FROM    t_info                     AS t1
        LEFT OUTER JOIN order_view AS v1
        ON (t1.id = v1.id)
WHERE   t1.status = 1
ORDER BY quantity DESC

ちなみにOracleではNVL(),MySQLではifnull()だそうです。

PostgreSQLの設定

■初期設定

まずは自動起動をonにします。

# /sbin/chkconfig postgresql on

次にとりあえずサーバを起動します。

# /etc/init.d/postgresql start

初期化が終了しサーバが起動します。
そしたら、次はUNIXのpostgresユーザのパスワードを設定します。

# passwd postgres
Changing password for user postgres.
New UNIX password:
Retype new UNIX password:
passwd: all authentication tokens updated successfully.

続いてPostgreSQL 内で管理するスーパーユーザー postgres にパスワードを設定します。
こちらは先ほどの Unix アカウントとは異なります。
インストール時に事前に用意されているデータベース template1 にpsql コマンドで接続します。
(psql の実行は必ずデータベースに接続する必要がある) また、# はスーパーユーザー権限でデータベースに接続していることを示します。

# su - postgres
-bash-3.00$ psql template1
Welcome to psql 8.1.11, the PostgreSQL interactive terminal.

Type:  copyright for distribution terms
       h for help with SQL commands
       ? for help with psql commands
       g or terminate with semicolon to execute query
       q to quit

template1=# alter user postgres password 'パスワード';
ALTER ROLE
template1=# q
-bash-3.00$ logout

次に、いつも使うユーザを追加します。

# su - postgres
-bash-3.00$ createuser -P
Enter name of role to add: webmaster
Enter password for new role: パスワードを入力
Enter it again: 入力したパスワードの確認
Shall the new role be a superuser? (y/n) y #スーパーユーザー特権を許可するかどうかです。
CREATE ROLE

webmasterの部分はお好きなユーザ名に変更して下さい。

次に、PostgreSQL認証設定ファイルを編集

-bash-3.00$ vi /var/lib/pgsql/data/pg_hba.conf

以下の部分を変更
local all all md5
host all all 127.0.0.1/32 md5
 (アクセスはユーザ認証)

保存する

-bash-3.00$ logout
# /etc/init.d/postgresql restart (再起動)
postgresql サービスを停止中:                               [  OK  ]
postgresql サービスを開始中:                               [  OK  ]

# psql -U webmaster template1

として、ログインできればOKです。