2013-08-06 - Postgres Tips and Tricks
2013-08-06 - Postgres Tips and Tricks
2013-08-06 - Postgres Tips and Tricks
By Lloyd Albin
5/1/2013, 6/11/2013
Why does my query run slow
SELECT max(l1.upload_timestamp) AS LastUploadTimestamp,
lcase(l1.network) as network,
l1.filename, count(l1.file_id) AS NumberUploads
FROM lab_upload_log AS l1
GROUP BY lcase(l1.network), l1.filename
Create an index for the field if you are going to use the field in a WHERE clause
or a GROUP BY clause.
Why does my query run slow
SELECT ucase(final_lab_upload_log.lab) AS lab,
count(final_lab_upload_log.filename) AS "# Unique Files",
max(x.NumUploads) AS "Total # Uploads“
FROM final_lab_upload_log
LEFT JOIN (
SELECT count(lab_upload_log.filename) AS NumUploads,
ucase(lab_upload_log.lab) AS lab
FROM lab_upload_log
WHERE lcase(lab_upload_log.network)='vtn‘
AND lab_upload_log.upload_timestamp > (curdate() - 30)
GROUP BY ucase(lab_upload_log.lab)) AS x
ON x.lab = final_lab_upload_log.lab
WHERE final_lab_upload_log.LastUploadTimestamp > (curdate() - 30)
GROUP BY ucase(final_lab_upload_log.lab)
Remove doubling of the ucase. The doubling stops the index from being
used.
5 seconds (individually)
But in reality, we have three of these types of queries and so they take over:
15 seconds combined
Lab # Unique Total # Files # Unique Total # Files # Unique Total # Files
Files Uploaded Files Uploaded Files Uploaded
FH 2 2 55 56
HV 198 202
SA 10 10 54 54
v t 500
100 100 v t
SELECT * FROM table
398 398 100 100
WHERE t != ‘398’
500 null
null
v t
SELECT * FROM table
100 100
WHERE v != 398
OR v IS NULL 500
null
-- 833 rows returned (execution time: 32 ms; total time: 93 ms) -- 14,719 rows in finance_feeds.ps_job
Fast way to get current job
SELECT * FROM
(
SELECT DISTINCT ON (emplid, empl_rcd) *
FROM finance_feeds.ps_job
ORDER BY emplid, empl_rcd, effdt DESC, effseq DESC
)a
WHERE a.empl_status::text <> 'T' ::text;
https://www.labkey.o
rg/wiki/home/Docu
mentation/page.view
DISTINCT ON Query ?name=labkeySql
Query plan is almost ½ the speed and only scans the table once instead of three times.
How to compare two queries
There is a great command called EXCEPT. This will compare the results of two queries
and tell you what is in the first query that is not in the second query.
This will show you all lines in view_a that are not in view_b. To find out all lines
on view_b that are not in view_a, reverse the two queries. If you are comparing
two complex query statements, wrap them in a simple SELECT statement so
that the EXCEPT will not get confused.
How to compare two queries
There is a great command called EXCEPT. This will compare the results of two queries
and tell you what is in the first query that is not in the second query.
SELECT * FROM (
SELECT 1
UNION
SELECT 2
)a
EXCEPT
SELECT * FROM (
SELECT 1
UNION
SELECT 3 ?Column?
)b
2
How to compare two queries
Normally you will also want to reverse the two queries so that you can check the results going
the other direction. This way you have two sets of results, what is extra in each query.
SELECT * FROM (
SELECT 1
UNION
SELECT 3
)b
EXCEPT
SELECT * FROM (
SELECT 1
UNION ?Column?
SELECT 2
3
)a
How to compare two queries
If you want only the records that match, then you want to use INTERSECT.
SELECT * FROM (
SELECT 1
UNION
SELECT 3
)b
INTERSECT
SELECT * FROM (
SELECT 1
UNION
SELECT 2 ?Column?
)a
1
Finding the slow line in your query
EXPLAIN will show you the query plan, and this by itself is helpful, but even more
helpful is the EXPLAIN (ANALYZE, BUFFERS) which compares the query plan to what
actually happened when the query was run. Also use http://explain.depesz.com/
1) Estimate rows=1 vers Actual rows=10983. When you have big difference
between these numbers, this is a sign of a problem. This can be caused by
not having enough statistics, not having an index, etc.
2) Actual time=1871.328..9912784.289. This means that this row started 1.87
seconds into the query and took the difference of the two times, 2.64
hours, to complete
Number of months between dates
date_trunc(‘month’, date) -- First day of the month
date + ‘1 day’::interval -- Converts last day of the month to the first day of next month
age(date, date) -- The difference between two timestamps as an interval
date_part(‘year’, date/interval) -- returns only the year portion of the date/interval
SELECT
(date_part('year', age(max(b.earnenddate)::timestamp + interval '1 day',
date_trunc('month',min(b.earnenddate)::date)::timestamp))*12 +
date_part('month', age(max(b.earnenddate)::timestamp + interval '1 day',
date_trunc('month',min(b.earnenddate)::date)::timestamp)))::integer
AS elapsed_months
FROM (
SELECT '06/30/2012' AS earnenddate
UNION
SELECT '12/31/2013' AS earnenddate
) b; elapsed_months
19
Creating a Table from a View
CREATE TABLE schema.table AS
SELECT * FROM schema.view;
This allows you to create a table without having to look up all the field
names and types to first generate a table and then fill it with the results
of the view.
TRUNCATE schema.table;
COMMIT;
This allows you to take the results of a view and append them to an
existing table.
You may wish to TRUNCATE schema.table before adding the new data.
What order is my data in?
When you don’t use an ORDER BY clause, your data is in physical order of insert and
update.
key test
1 f
3 f
2 t
ORDER BY field
Normally you use ORDER BY field_name, but you can also use ORDER BY field_number.
I have found this to sometimes be useful when unioning one or more sets of data
together.
Notes:
ORDER BY test1 will work.
ORDER BY test2 will not work.
UNION ALL gives you all rows from each SELECT and runs much faster.
UNION only gives you DISTINCT rows between the two tables and ordered
TRUNCATE vers DELETE
TRUNCATE is normally the best way to go because it removes all the data within the
table(s) quickly and by specifying more than one table, deals automatically with
foreign key dependencies. Delete can take a long time depending on the foreign key
dependencies, etc.
TRUNCATE is not MVCC-save, so after truncation, the table will appear empty to all
concurrent transactions, even if they are using a snapshot taken before the truncation
occurred. DELETE does not have this issue.
RESTART IDENTITY
Automatically restart sequences owned by columns of the truncated table(s).
test1
test2
test5
pg_stat_activity 9.1-
SELECT * FROM pg_stat_activity;
waiting current_query
False SELECT * FROM pg_stat_activity
This will show you what queries that you currently have running on a server. As
user Postgres, you will see all queries running on a server. If there is no query
running, you will see <IDLE>.
Postgres Tips & Tricks
POSTGRES 9.2+
pg_stat_activity 9.2+
SELECT * FROM pg_stat_activity;
waiting current_query
False <idle>: SELECT * FROM pg_stat_activity
This will show you what queries that you currently have running on a server. As
user Postgres, you will see all queries running on a server. They will also say
<idle> or <active>. The <idle> connections show you the last query executed.
Killing your own backend’s
SELECT pg_cancel_backend(pid);
This cancels your current command and leaves your connection open
for your next command. If you are in the middle of a transaction, the
transaction will be aborted once you try and COMMIT your transaction.
It will also complain about every line failing until you try and COMMIT.
SELECT pg_terminate_backend(pid);
This cancels your current command and closes your connection. If you
are in the middle of a transaction, the transaction will be aborted
instantly.
If all the backends you see are gone and you are still getting the open
connections when trying to drop your database, contact a dba.
Postgres Tips & Tricks
POSTGRES 9.3+
Materialized Views
CREATE MATERIALIZED VIEW schema.materialized_view AS
SELECT * FROM schema.table;