Created
September 19, 2019 08:41
-
-
Save lukaseder/2611212b23ba40d5f828c69b79214a0e to your computer and use it in GitHub Desktop.
COUNT(*) vs COUNT(1) in PostgreSQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Copyright Data Geekery GmbH | |
-- | |
-- Licensed under the Apache License, Version 2.0 (the "License"); | |
-- you may not use this file except in compliance with the License. | |
-- You may obtain a copy of the License at | |
-- | |
-- http://www.apache.org/licenses/LICENSE-2.0 | |
-- | |
-- Unless required by applicable law or agreed to in writing, software | |
-- distributed under the License is distributed on an "AS IS" BASIS, | |
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
-- See the License for the specific language governing permissions and | |
-- limitations under the License. | |
-- | |
CREATE TABLE t (i INT); | |
INSERT INTO t SELECT i FROM generate_series(1, 1000000) AS d(i); | |
DO $$ | |
DECLARE | |
v_ts TIMESTAMP; | |
v_repeat CONSTANT INT := 100; | |
rec RECORD; | |
run INT[]; | |
stmt INT[]; | |
elapsed DECIMAL[]; | |
min_elapsed DECIMAL; | |
i INT := 1; | |
BEGIN | |
-- Repeat the whole benchmark several times to avoid warmup penalty | |
FOR r IN 1..5 LOOP | |
v_ts := clock_timestamp(); | |
FOR i IN 1..v_repeat LOOP | |
FOR rec IN ( | |
SELECT COUNT(*) FROM t | |
) LOOP | |
NULL; | |
END LOOP; | |
END LOOP; | |
run[i] := r; | |
stmt[i] := 1; | |
elapsed[i] := (EXTRACT(EPOCH FROM CAST(clock_timestamp() AS TIMESTAMP)) - EXTRACT(EPOCH FROM v_ts)); | |
i := i + 1; | |
v_ts := clock_timestamp(); | |
FOR i IN 1..v_repeat LOOP | |
FOR rec IN ( | |
SELECT COUNT(1) FROM t | |
) LOOP | |
NULL; | |
END LOOP; | |
END LOOP; | |
run[i] := r; | |
stmt[i] := 2; | |
elapsed[i] := (EXTRACT(EPOCH FROM CAST(clock_timestamp() AS TIMESTAMP)) - EXTRACT(EPOCH FROM v_ts)); | |
i := i + 1; | |
END LOOP; | |
SELECT min(t.elapsed) | |
INTO min_elapsed | |
FROM unnest(elapsed) AS t(elapsed); | |
FOR i IN 1..array_length(run, 1) LOOP | |
RAISE INFO 'RUN %, Statement %: %', run[i], stmt[i], CAST(elapsed[i] / min_elapsed AS DECIMAL(10, 5)); | |
END LOOP; | |
RAISE INFO ''; | |
RAISE INFO 'Copyright Data Geekery GmbH'; | |
RAISE INFO 'https://www.jooq.org/benchmark'; | |
END$$; | |
DROP TABLE t; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment