首页 > 解决方案 > SQL - Looking for a specific name without going through all the table

问题描述

There is a student table and you are looking for all the students having a particular name.

How to do it without going through the whole table?

How would you approach this kind of question? please add complexity

标签: sql

解决方案


这是 SQL 中的常见问题。首先,您只需将查询编写为:

select s.*
from students s
where s.name = ?;

然后 SQL 提供了两种优化此类查询的方法。到目前为止,最常见的是使用索引:

create index idx_students_name on students(name);

可能还有其他方法可以有效地创建相同的索引。这将直接加快查询速度。但是,在小表上,某些数据库可能不使用索引,因为它们计算出顺序扫描更有效。

另一种方法是对表进行分区name。这实际上只在非常大的表上很常见,并且分区键通常是日期/时间值。

请记住:SQL 是一种描述性语言,而不是一种过程性语言。SQL 查询描述结果集。优化阶段确定引擎为达到结果集所采取的确切步骤。


推荐阅读