如何有效地确定Postgres表是否有行

时间:2008-10-24 15:57:19

标签: postgresql

我做了这个测试,结果看起来计数函数是线性的。我有另一个功能强烈依赖效率来知道是否有任何数据,所以我想知道如何用另一个更有效(可能是常量?)的查询或数据结构替换这个选择计数(*)。

  

psql -d testdb -U postgres -f truncate_and_insert_1000_rows.sql> NUL

     

psql -d testdb -U postgres -f count_data.sql

----------------------------------------------- ---------------------------------

聚合(成本= 36.75..36.76行= 1宽度= 0)(实际时间= 0.762..0.763行= 1 循环= 1)     - > Seq扫描数据(成本= 0.00..31.40行= 2140宽度= 0)(实际时间= 0.02 8..0.468行= 1000个循环= 1)  总运行时间: 0.846 ms (3菲拉斯)

  

psql -d testdb -U postgres -f truncate_and_insert_10000_rows.sql> NUL

     

psql -d testdb -U postgres -f count_data.sql

----------------------------------------------- ---------------------------------

汇总(成本= 197.84..197.85行= 1宽度= 0)(实际时间= 6.191..6.191行= 1个循环= 1)     - > Seq Scan on datos(cost = 0.00..173.07 rows = 9907 width = 0)(实际时间= 0.0 09..3.407行= 10000循环= 1)  总运行时间: 6.271 ms (3菲拉斯)

  

psql -d testdb -U postgres -f truncate_and_insert_100000_rows.sql> NUL

     

psql -d testdb -U postgres -f count_data.sql

----------------------------------------------- ---------------------------------

汇总(成本= 2051.60..2051.61行= 1宽度= 0)(实际时间= 74.075..74.076 r ows = 1个循环= 1)     - > Seq Scan on datos(cost = 0.00..1788.48 rows = 105248 width = 0)(实际时间= 0.032..46.024行= 100000个循环= 1)  总运行时间: 74.164 ms (3菲拉斯)

  

psql -d prueba -U postgres -f truncate_and_insert_1000000_rows.sql> NUL

     

psql -d testdb -U postgres -f count_data.sql

----------------------------------------------- ---------------------------------

汇总(成本= 19720.00..19720.01行= 1宽度= 0)(实际时间= 637.486..637.4 87行= 1个循环= 1)     - > Seq Scan on datos(cost = 0.00..17246.60 rows = 989360 width = 0)(实际时间 = 0.028..358.831行= 1000000个循环= 1)  总运行时间: 637.582 ms (3菲拉斯)

数据的定义是

CREATE TABLE data
(
  id INTEGER NOT NULL,
  text VARCHAR(100),
  CONSTRAINT pk3 PRIMARY KEY (id)
);

6 个答案:

答案 0 :(得分:11)

从表限制1中选择true;

答案 1 :(得分:3)

select exists(select * from your_table_here) as has_row

答案 2 :(得分:1)

如果你关心的只是1行或没有行。将查询限制在第一行 - 为什么要计算所有行只是为了找出是否有1或更多,或者为零......

使用相当于ROWNUM = 1或TOP 1或者postgres给你的东西。

答案 3 :(得分:1)

您可能会发现this有用。

答案 4 :(得分:1)

试试这个:

SELECT t.primary_key IS NOT NULL FROM table t LIMIT 1;

如果有记录,您将获得TRUE,如果没有,则为NULL。

答案 5 :(得分:0)

如何计算主键字段为NOT NULL,将查询限制为1响应?

由于主键必须存在,如果有,你有数据,是吗?