Home > Database > SQL > Usage of having and where in sql

Usage of having and where in sql

下次还敢
Release: 2024-05-02 02:33:17
Original
1219 people have browsed it

The WHERE clause filters rows in the SELECT statement and filters the underlying data based on row conditions. The HAVING clause filters groups in a GROUP BY statement, filtering groups based on their aggregate results. The main differences: WHERE processes individual rows and evaluates the conditions of the rows; HAVING processes groups and evaluates the aggregated results of the groups; WHERE affects which rows are included in the results, and HAVING affects which groups are included in the results.

Usage of having and where in sql

WHERE and HAVING clauses are used in SQL

WHERE and HAVING clauses are used in SQL Filter datasets, but they differ in processing context and target:

#WHERE clause:

  • The WHERE clause is used in the SELECT statement Filter rows after FROM.
  • It evaluates rows in the underlying table or view based on conditions for each row.
  • It is used to filter the underlying data, thereby affecting which rows are included in the final result.

Example:

<code class="sql">SELECT * FROM employees WHERE salary > 50000;</code>
Copy after login

This query returns all employees with a salary greater than $50,000.

HAVING CLAUSE: The

  • HAVING clause is used to filter groups in a GROUP BY statement.
  • It evaluates groups based on their aggregated results.
  • It is used to filter groups, thereby affecting which groups are included in the final result.

Example:

<code class="sql">SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING total_salary > 100000;</code>
Copy after login

This query returns the total salary for all departments where the total salary is greater than $100,000.

Main differences:

  • Processing context: The WHERE clause processes individual rows, while the HAVING clause processes groups.
  • Evaluation target: The WHERE clause evaluates the condition on a single row, while the HAVING clause evaluates the aggregated results of the group.
  • Result Impact: The WHERE clause affects which rows are included in the result, and the HAVING clause affects which groups are included in the result.

The above is the detailed content of Usage of having and where in sql. 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