In SQL, what is the difference between the WHERE clause and the HAVING clause? Can you provide an example with a sample table structure and data?
The WHERE clause is used to filter rows based on conditions before grouping and aggregating the data, while the HAVING clause is used to filter groups based on conditions after grouping and aggregating the data. Here's an example to illustrate this: Consider a sample table 'Sales' with columns 'Product', 'Region', and 'TotalSales'. To retrieve the regions with total sales greater than 1000, you would use the following SQL query: SELECT Region, SUM(TotalSales) AS TotalSales FROM Sales WHERE TotalSales > 1000 GROUP BY Region HAVING TotalSales > 5000;
The WHERE clause is used to filter rows based on conditions at the individual row level, while the HAVING clause is used to filter groups based on conditions after grouping the data. For instance, let's say we have a sample table 'Employees' with columns 'Name', 'Department', and 'Salary'. To retrieve the departments with an average salary greater than 50000, the SQL query would be: SELECT Department, AVG(Salary) AS AverageSalary FROM Employees GROUP BY Department HAVING AVG(Salary) > 50000;
-
Data Literacy 2024-08-04 11:49:07 In the context of Data Literacy, what do we mean by 'data governance'?
-
Data Literacy 2024-07-23 14:31:22 How can fuzzy logic be applied to solve real-world problems?