Home > Database > Mysql Tutorial > SELECT 1 vs. SELECT * in EXISTS Subqueries: Does it Matter for Performance?

SELECT 1 vs. SELECT * in EXISTS Subqueries: Does it Matter for Performance?

Barbara Streisand
Release: 2025-01-15 20:14:42
Original
884 people have browsed it

SELECT 1 vs. SELECT * in EXISTS Subqueries: Does it Matter for Performance?

*EXISTS subquery optimization: performance difference between SELECT 1 and SELECT **

When using the EXISTS operator in a SQL query, there is a dispute about whether to specify SELECT 1 or SELECT * in the subquery. This article explores the performance impact of both approaches.

**Traditional method: SELECT ***

Traditionally, subqueries use SELECT * because it retrieves all columns in the subquery.

<code class="language-sql">IF EXISTS (SELECT * FROM TABLE WHERE Columns=@Filters)
BEGIN
   UPDATE TABLE SET ColumnsX=ValuesX WHERE Columns=@Filters
END</code>
Copy after login

Alternative method: SELECT 1

Database experts recommend that for EXISTS checks, using SELECT 1 is more efficient since it only returns a single value.

<code class="language-sql">IF EXISTS (SELECT 1 FROM TABLE WHERE Columns=@Filters)
BEGIN
   UPDATE TABLE SET ColumnsX=ValuesX WHERE Columns=@Filters
END</code>
Copy after login

Performance Difference

Despite the purported potential performance benefits of SELECT 1, Microsoft SQL Server is designed to optimize subqueries of the EXISTS operator. Whether you use SELECT 1 or SELECT *, SQL Server does not return data to the system.

Verification

To verify this optimization, try executing the following query:

<code class="language-sql">SELECT whatever
  FROM yourtable
 WHERE EXISTS( SELECT 1/0
                 FROM someothertable 
                WHERE a_valid_clause )</code>
Copy after login

No error will be thrown even if the subquery performs an invalid division. This indicates that the EXISTS list in the SELECT subquery will not be evaluated.

SQL Standard

The ANSI SQL 1992 standard clearly states that when a SELECT list contains only "*" in the EXISTS subquery, it is equivalent to an arbitrary literal.

Conclusion

Based on SQL Server's optimization capabilities and SQL standards, there is no performance difference when using SELECT 1 or SELECT * in an EXISTS subquery. Both methods will return the same results with equal efficiency.

The above is the detailed content of SELECT 1 vs. SELECT * in EXISTS Subqueries: Does it Matter for Performance?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template