PostgreSQL WHERE 和 ORDER BY 子句的时间复杂度

标签 postgresql

假设我们在 PostgteSQL 表 table1 上运行以下查询,其中列 col1 通过 b 树索引...

SELECT * FROM table1 WHERE col1='foo' ORDER BY col2;

查询的时间复杂度是否等于...

O(log(n) + m*log(m))

给定的ntable1中的行数,m是满足where子句的行数?

最佳答案

假设使用 O(n log n) 排序算法...

如果它确实使用索引,那么是的,搜索 B 树的时间复杂度为 O(log n),排序行的时间复杂度为 O(m log m)。

但是,数据库是一个不能忽略常量的情况。与顺序扫描相比,索引查找的常数相对较高。如果表的大部分与 col1='foo' 匹配,Postgres 可能会认为全表扫描 O(n) 比索引更快,因为它的常数较低。那么就是 O(n + m log m)。

此外,m的大小会影响是否使用文件排序或内存排序,从而极大地影响效率。

关于PostgreSQL WHERE 和 ORDER BY 子句的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61996844/

相关文章:

postgresql - Psycopg2 SQL 语句在查询生成器中工作,而不是在 Python 中工作

python - Django - 批量更新 arrayfield 行 postgres

c# - 转换方法。 "The specified method on the type cannot be translated into a LINQ to Entities store expression"

postgresql - sonar V.4.3.1 不启动postgresql

postgresql - Postgres 函数(通过 npgsql)调用 ExecuteNonQuery 返回 -1 作为受影响行的结果

php - 使用 SQL 命令为价格范围创建下拉框

postgresql - 按日期范围对结果进行分组

apache - Phusion Passenger 内部服务器错误

SQL子查询使用主查询中的逐项分组

python - Django 设置 DigitalOcean Postgres "DATABASES = {"错误