# 表结构
```pgsql
-- ----------------------------
-- Table structure for t_test
-- ----------------------------
DROP TABLE IF EXISTS "public"."t_test";
CREATE TABLE "public"."t_test" (
"id" int4 NOT NULL,
"name" varchar(50) COLLATE "pg_catalog"."default",
"desc" varchar(50) COLLATE "pg_catalog"."default",
"age" int4,
"sort" int4
)
;
-- ----------------------------
-- Indexes structure for table t_test
-- ----------------------------
CREATE INDEX "idx_test_age" ON "public"."t_test" USING btree (
"age" "pg_catalog"."int4_ops" ASC NULLS LAST
);
CREATE INDEX "idx_test_name" ON "public"."t_test" USING btree (
"name" COLLATE "pg_catalog"."default" "pg_catalog"."text_ops" ASC NULLS LAST
);
-- ----------------------------
-- Primary Key structure for table t_test
-- ----------------------------
ALTER TABLE "public"."t_test" ADD CONSTRAINT "t_test_pkey" PRIMARY KEY ("id");
```
## 插入测试数据
插入100000条测试数据
# 验证
<br/>
```pgsql
explain SELECT * FROM "t_test" where age= 25;
explain SELECT * FROM "t_test" where name like '%张三1%' or age= 25;
explain SELECT * FROM "t_test" where age= 25 or name like '%张三1%';
explain analyse SELECT * FROM "t_test" where age= 25
union
SELECT * FROM "t_test" where name like '%张三1%';
```

# 结论
pgsql中or条件中只要有一个条件存在前模糊都会破坏索引的使用
# 优化
用**union**去组合非索引条件或索引破坏条件字段替换**or**
本文探讨了pgsql数据库中索引对于查询性能的影响,指出当`or`条件包含非索引字段时,索引可能无法有效利用。建议使用`union`来替代`or`,以组合非索引条件,从而优化查询效率。通过示例展示了不同查询方式的执行计划,强调了优化查询语句在数据库性能调优中的重要性。
601

被折叠的 条评论
为什么被折叠?



