SQL statistical authorization - sql

I am trying to understand how statistical authorization works in SQL.

The query result must be a single
aggregate value.
This means you may only use SUM(salary) or COUNT(*) in the select list. If the ID was included, the individual employees can be identified.
At least 3 different tuples should be
used in the aggregate to produce each
query result
You can include a HAVING clause like this:
having count(distinct ID) >= 3
I don't understand the rest of the question.

Related

SQL Aggregate Functions -- HAVING vs WHERE

Context: I'm fiddling with SQL in SQLFiddle Postgres 9.6. I'm trying to apply aggregate functions to 2 columns in the outer query that are dependent on the existence of values from a subquery.
I'm having a hard time determining whether the query is correct using the WHERE clause instead of HAVING.The SQL executes but I'm not confident that it's generating the intended results.
Question: Can someone help me understand if this is the correct way to perform the aggregation? And if not how can I modify the query to get the intended results if including HAVING requires GROUPING BY user_id in the outer query which kinda defeats the purpose.
Intended Results: I want to count the number of actions a user takes before progressing to a new action. I only want to count the number of Read Article events if a user (user_id) made it to the next action (View Product) I'm going to use the aggregation to calculate some averages.
Sample output:
Query:
SELECT event_type as action_a,
COUNT(event_type) as action_a_count,
COUNT(DISTINCT user_id) as unique_users
FROM events
WHERE event_type in ('Read Article')
AND user_id in
(
SELECT DISTINCT(user_id) as user_id
FROM events
WHERE event_type in ('View Product')
)
GROUP BY event_type
Your query is good. With WHERE event_type = 'Read Article' you filter events rows. Thus only those rows must be aggregated.
You could use HAVING event_type = 'Read Article' instead, because you are grouping by that column, too. That would mean you would first look up users for all rows and would aggregate over all desired user rows and only then dismiss undesired event_types. This would give the DBMS much more work to do.
Conclusion: Use WHERE to reduce the rows as soon as possible, so the DBMS can work on smaller data sets. This will Speed up your queries.
HAVING and WHERE do appear to have overlap but there are differences, WHERE checks a row for equality whereas HAVING is used to check against aggregate sets, the most basic example would be finding duplicates in a table with a
SELECT column_name, count(*)
FROM table_name
GROUP BY column_name
HAVING count(*) > 1
This query would need to count the rows before filtering, thus uses HAVING. In your case, filtering for equality using WHERE is fine because it only needs to take a single row into account.

Subquery requiring group by without single row function

From my understanding queries that rely on one or more aggregate functions as well as at least one single row function require the single row functions to be placed
in a group by clause, which makes sense overall.
However I'm working through problems in an online resource and ran into the question in the picture, my logic behind why I answered it executes successfully but gives improper output is that the subquery is a query that has only an aggregate function, leaving me to believe that it requires no group by, why is it that this requires a group by in the subquery?
Already cleared by Gordon, "Nested aggregate requires a GROUP BY clause". If we consider the query into 2 parts, first part works fine if Having is given with specific value.
Example:
Run Queries in this link:
https://livesql.oracle.com/apex/f?p=590:1:104596775146183::NO:RP::
select count(*), PROD_CATEGORY_ID from SH.PRODUCTS group by PROD_CATEGORY_ID
having count(*)>15;
But we get error if we combine 2 aggregate functions,
select max(count(PROD_CATEGORY_ID)) from SH.PRODUCTS ; --> Throws ORA-00978
select max(count(PROD_CATEGORY_ID)) from SH.PRODUCTS
group by PROD_CATEGORY_ID; -->Gives max count of prod_cat
Gives final result:
select count(*), PROD_CATEGORY_ID from SH.PRODUCTS
group by PROD_CATEGORY_ID
having count(*)=(select max(count(*)) from SH.PRODUCTS group by PROD_CATEGORY_ID);
Good Examples in link:
https://mahtodeepak05.wordpress.com/2014/12/17/aggregate-function-nesting-in-oracle/
You can easily test this:
select max(count(*))
from dual;
The error is:
ORA-00978: nested group function without GROUP BY
So, a nested group by seems to require a GROUP BY.

Why are aggregate functions not allowed in where clause

I am looking for clarification on this. I am writing two queries below:
We have a table of employee name with columns ID , name , salary
1. Select name from employee
where sum(salary) > 1000 ;
2. Select name from employee
where substring_index(name,' ',1) = 'nishant' ;
Query 1 doesn't work but Query 2 does work. From my development experience, I feel the possible explanation to this is:
The sum() works on a set of values specified in the argument. Here
'salary' column is passed , so it must add up all the values of this
column. But inside where clause, the records are checked one by one ,
like first record 1 is checked for the test and so on. Thus
sum(salary) will not be computed as it needs access to all the column
values and then only it will return a value.
Query 2 works as substring_index() works on a single value and hence here it works on the value supplied to it.
Can you please validate my understanding.
The reason you can't use SUM() in the WHERE clause is the order of evaluation of clauses.
FROM tells you where to read rows from. Right as rows are read from disk to memory, they are checked for the WHERE conditions. (Actually in many cases rows that fail the WHERE clause will not even be read from disk. "Conditions" are formally known as predicates and some predicates are used - by the query execution engine - to decide which rows are read from the base tables. These are called access predicates.) As you can see, the WHERE clause is applied to each row as it is presented to the engine.
On the other hand, aggregation is done only after all rows (that verify all the predicates) have been read.
Think about this: SUM() applies ONLY to the rows that satisfy the WHERE conditions. If you put SUM() in the WHERE clause, you are asking for circular logic. Does a new row pass the WHERE clause? How would I know? If it will pass, then I must include it in the SUM, but if not, it should not be included in the SUM. So how do I even evaluate the SUM condition?
Why can't we use aggregate function in where clause
Aggregate functions work on sets of data. A WHERE clause doesn't have access to entire set, but only to the row that it is currently working on.
You can of course use HAVING clause:
select name from employee
group by name having sum(salary) > 1000;
If you must use WHERE, you can use a subquery:
select name from (
select name, sum(salary) total_salary from employee
group by name
) t where total_salary > 1000;
sum() is an aggregation function. In general, you would expect it to work with group by. Hence, your first query is missing a group by. In a group by query, having is used for filtering after the aggregation:
Select name
from employee
group by name
having sum(salary) > 1000 ;
Using having works since the query goes direct to the rows in that column while where fails since the query keep looping back and forth whenever conditions is not met.

Is there any difference to use group by in a query ?

I have a query
SELECT bk_publisher, bk_price FROM books
GROUP BY bk_price, bk_publisher
and
SELECT bk_publisher ,bk_price FROM books
both are returning the same results. Means i have 12 records in my table and both queries returning the 12 records. What is the difference ? Although i am using group by, which is use with aggregate functions. But i want to know is group by making any difference here ?
SELECT bk_publisher, bk_price FROM books
GROUP BY bk_price, bk_publisher
Will result distinct pairs of (publisher, price), even if your table contains duplicated data.
SQL group by helps you group different results by some identical value (using aggregation functions on other values)
In your case it doesn't mean anything, but when you want to aggregate values based on identical field, you use group by.
For example, if you want to get the max price of a publisher:
SELECT bk_publisher, max(bk_price) FROM books
GROUP BY bk_publisher
The GROUP BY statement is used to group the result-set by one or more columns.Group by is used when you have repeating data and you want single record for each entry.
When you use GROUP BY, it will squeeze multiple rows having identical columns listed in GROUP BY as single row in output.
It also means that in general, all other columns mentioned in SELECT list must be wrapped in aggregate functions like sum(), avg(), count(), etc.
Some SQL engines like MySQL permit not using aggregates, but many people consider this a bug.
GROUP BY clause is apparently showing no effect because there is no repeating combination of bk_price, bk_publisher values.

What is the difference between HAVING and WHERE in SQL?

What is the difference between HAVING and WHERE in an SQL SELECT statement?
EDIT: I have marked Steven's answer as the correct one as it contained the key bit of information on the link:
When GROUP BY is not used, HAVING behaves like a WHERE clause
The situation I had seen the WHERE in did not have GROUP BY and is where my confusion started. Of course, until you know this you can't specify it in the question.
HAVING: is used to check conditions after the aggregation takes place.
WHERE: is used to check conditions before the aggregation takes place.
This code:
select City, CNT=Count(1)
From Address
Where State = 'MA'
Group By City
Gives you a table of all cities in MA and the number of addresses in each city.
This code:
select City, CNT=Count(1)
From Address
Where State = 'MA'
Group By City
Having Count(1)>5
Gives you a table of cities in MA with more than 5 addresses and the number of addresses in each city.
HAVING specifies a search condition for a
group or an aggregate function used in SELECT statement.
Source
Number one difference for me: if HAVING was removed from the SQL language then life would go on more or less as before. Certainly, a minority queries would need to be rewritten using a derived table, CTE, etc but they would arguably be easier to understand and maintain as a result. Maybe vendors' optimizer code would need to be rewritten to account for this, again an opportunity for improvement within the industry.
Now consider for a moment removing WHERE from the language. This time the majority of queries in existence would need to be rewritten without an obvious alternative construct. Coders would have to get creative e.g. inner join to a table known to contain exactly one row (e.g. DUAL in Oracle) using the ON clause to simulate the prior WHERE clause. Such constructions would be contrived; it would be obvious there was something was missing from the language and the situation would be worse as a result.
TL;DR we could lose HAVING tomorrow and things would be no worse, possibly better, but the same cannot be said of WHERE.
From the answers here, it seems that many folk don't realize that a HAVING clause may be used without a GROUP BY clause. In this case, the HAVING clause is applied to the entire table expression and requires that only constants appear in the SELECT clause. Typically the HAVING clause will involve aggregates.
This is more useful than it sounds. For example, consider this query to test whether the name column is unique for all values in T:
SELECT 1 AS result
FROM T
HAVING COUNT( DISTINCT name ) = COUNT( name );
There are only two possible results: if the HAVING clause is true then the result with be a single row containing the value 1, otherwise the result will be the empty set.
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.
Check out this w3schools link for more information
Syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
A query such as this:
SELECT column_name, COUNT( column_name ) AS column_name_tally
FROM table_name
WHERE column_name < 3
GROUP
BY column_name
HAVING COUNT( column_name ) >= 3;
...may be rewritten using a derived table (and omitting the HAVING) like this:
SELECT column_name, column_name_tally
FROM (
SELECT column_name, COUNT(column_name) AS column_name_tally
FROM table_name
WHERE column_name < 3
GROUP
BY column_name
) pointless_range_variable_required_here
WHERE column_name_tally >= 3;
The difference between the two is in the relationship to the GROUP BY clause:
WHERE comes before GROUP BY; SQL evaluates the WHERE clause before it groups records.
HAVING comes after GROUP BY; SQL evaluates HAVING after it groups records.
References
SQLite SELECT Statement Syntax/Railroad Diagram
Informix SELECT Statement Syntax/Railroad Diagram
HAVING is used when you are using an aggregate such as GROUP BY.
SELECT edc_country, COUNT(*)
FROM Ed_Centers
GROUP BY edc_country
HAVING COUNT(*) > 1
ORDER BY edc_country;
WHERE is applied as a limitation on the set returned by SQL; it uses SQL's built-in set oeprations and indexes and therefore is the fastest way to filter result sets. Always use WHERE whenever possible.
HAVING is necessary for some aggregate filters. It filters the query AFTER sql has retrieved, assembled, and sorted the results. Therefore, it is much slower than WHERE and should be avoided except in those situations that require it.
SQL Server will let you get away with using HAVING even when WHERE would be much faster. Don't do it.
WHERE clause does not work for aggregate functions
means : you should not use like this
bonus : table name
SELECT name
FROM bonus
GROUP BY name
WHERE sum(salary) > 200
HERE Instead of using WHERE clause you have to use HAVING..
without using GROUP BY clause, HAVING clause just works as WHERE clause
SELECT name
FROM bonus
GROUP BY name
HAVING sum(salary) > 200
Difference b/w WHERE and HAVING clause:
The main difference between WHERE and HAVING clause is, WHERE is used for row operations and HAVING is used for column operations.
Why we need HAVING clause?
As we know, aggregate functions can only be performed on columns, so we can not use aggregate functions in WHERE clause. Therefore, we use aggregate functions in HAVING clause.
One way to think of it is that the having clause is an additional filter to the where clause.
A WHERE clause is used filters records from a result. The filter occurs before any groupings are made. A HAVING clause is used to filter values from a group
In an Aggregate query, (Any query Where an aggregate function is used) Predicates in a where clause are evaluated before the aggregated intermediate result set is generated,
Predicates in a Having clause are applied to the aggregate result set AFTER it has been generated. That's why predicate conditions on aggregate values must be placed in Having clause, not in the Where clause, and why you can use aliases defined in the Select clause in a Having Clause, but not in a Where Clause.
I had a problem and found out another difference between WHERE and HAVING. It does not act the same way on indexed columns.
WHERE my_indexed_row = 123 will show rows and automatically perform a "ORDER ASC" on other indexed rows.
HAVING my_indexed_row = 123 shows everything from the oldest "inserted" row to the newest one, no ordering.
When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.
However, when GROUP BY is used:
The WHERE clause is used to filter records from a result. The
filtering occurs before any groupings are made.
The HAVING clause is used to filter values from a group (i.e., to
check conditions after aggregation into groups has been performed).
Resource from Here
From here.
the SQL standard requires that HAVING
must reference only columns in the
GROUP BY clause or columns used in
aggregate functions
as opposed to the WHERE clause which is applied to database rows
While working on a project, this was also my question. As stated above, the HAVING checks the condition on the query result already found. But WHERE is for checking condition while query runs.
Let me give an example to illustrate this. Suppose you have a database table like this.
usertable{ int userid, date datefield, int dailyincome }
Suppose, the following rows are in table:
1, 2011-05-20, 100
1, 2011-05-21, 50
1, 2011-05-30, 10
2, 2011-05-30, 10
2, 2011-05-20, 20
Now, we want to get the userids and sum(dailyincome) whose sum(dailyincome)>100
If we write:
SELECT userid, sum(dailyincome) FROM usertable WHERE
sum(dailyincome)>100 GROUP BY userid
This will be an error. The correct query would be:
SELECT userid, sum(dailyincome) FROM usertable GROUP BY userid HAVING
sum(dailyincome)>100
WHERE clause is used for comparing values in the base table, whereas the HAVING clause can be used for filtering the results of aggregate functions in the result set of the query
Click here!
When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.
However, when GROUP BY is used:
The WHERE clause is used to filter records from a result. The
filtering occurs before any groupings are made.
The HAVING clause is
used to filter values from a group (i.e., to check conditions after
aggregation into groups has been performed).
I use HAVING for constraining a query based on the results of an aggregate function. E.G. select * in blahblahblah group by SOMETHING having count(SOMETHING)>0