Sunday, December 30, 2012

PostgreSQL - Copy CSV to table with psql - part 2


CREATE TABLE tbl_test
(
 a text,
 b text,
 c text
)
Content of test.csv, and it put in /Database folder
a1,b1,c1
a2,b2,c2
a3,b3,c3


Instead of using COPY command directly, you can modify the test.cvs file to include it, as
COPY tbl_test FROM STDIN WITH CSV;
a1,b1,c1
a2,b2,c2
a3,b3,c3

\.

Note that you have to include a carriage return in the last line of the file (after '\.')
Then, run the following command to import

MyComputer$ psql -h localhost -p 5432 -U postgres testdb -f ~/Database/test.csv

Thursday, December 13, 2012

PostgreSQL - Copy database

Sometimes, instead of back up and restore to a new db and wait your time if you only want to copy a database and put in the same server, you can use the following query:

CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser;
Note that this query only successfully if no sessions existing in originaldb. So, you can check originaldb sessions and kill them with this function pg_terminate_backend(procpid)

PostgreSQL - Kill idle processes

Sometimes, you need to kill all unnecessary processes running on your database server. You can do that by using the following query:

SELECT           
   procpid,
   (
       SELECT pg_terminate_backend(procpid)
   ) AS killed
 FROM pg_stat_activity
 WHERE current_query LIKE '%idle%' AND datname = 'YourDBName';

Sunday, December 9, 2012

PostgreSQL - Copy csv file to table with psql

CREATE TABLE tbl_test
(
 a text,
 b text,
 c text
)
Content of test.csv
a1,b1,c1
a2,b2,c2
a3,b3,c3

psql to COPY
psql -h localhost -U postgres testdb
testdb=# COPY tbl_test FROM 'D:\Temp\test.csv' WITH DELIMITER ',' CSV; 

PostgreSQL - VACUUM ANALYZE EXPLAIN NOTIFY

Select the correct statement that records the space occupied by deleted or updated rows for later reuse, and also updates statistics.

A. VACUUM
B. VACUUM ANALYZE
C. EXPLAIN
D. EXPLAIN ANALYZE
E. NOTIFY
F. None of the above

Answer: [B]
Highlight to find out the answer.

PostgreSQL - ANALYZE quiz

What does the following command do?
Choose the correct answer below.
Note: "psql=#" is the command prompt for psql.
psql=# ANALYZE xyz;

A. Collects statistical information related to the content of the database xyz.
B. Collects statistical information related to the content of the table xyz.
C. Outputs statistical information related to the content of the table xyz.
D. No ANALYZE command in PostgreSQL, error will occur.
E. None of the above
F. Both B & C

Answer: [B]
Highlight to find out the answer.

Friday, December 7, 2012

PostgreSQL – Convert rows to string

SELECT array_to_string(
    array(
        SELECT name
        FROM pg_settings
        WHERE setting = 'off' AND context = 'postmaster'
    ), ',');

SELECT setting, array_to_string(array_agg(name), ',')
FROM pg_settings
WHERE setting IN ('on', 'off')
GROUP BY setting;