Postgres SQL - Column does not exist [duplicate] - sql

This question already has answers here:
Using an Alias column in the where clause in Postgresql
(6 answers)
Closed 6 years ago.
SELECT nmemail as order_email,
dtorder,
vlOrder,
cohorts.cohortdate
FROM factorderline
JOIN (SELECT nmemail as cohort_email, Min(dtorder) AS cohortDate FROM factorderline GROUP BY cohort_email limit 5) cohorts
ON order_email= cohort_email limit 5;
ERROR: column "order_email" does not exist
What is the problem with this query?

The problem is most likely that the definition of the column alias hasn't been parsed at the time the join is evaluated; use the actual column name instead:
SELECT nmemail as order_email,
dtorder,
vlOrder,
cohorts.cohortdate
FROM factorderline
JOIN (
SELECT nmemail as cohort_email, Min(dtorder) AS cohortDate
FROM factorderline
GROUP BY cohort_email limit 5
) cohorts ON nmemail = cohort_email
limit 5;
Also, when using limit, you really should use an order by clause.
From the docs:
When using LIMIT, it is important to use an ORDER BY clause that
constrains the result rows into a unique order. Otherwise you will get
an unpredictable subset of the query's rows.

The problem is that output column names can't be used in joins.
From the documentation:
An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.

Related

&& Operator change the order of result [duplicate]

This question already has answers here:
Does order by in view guarantee order of select?
(3 answers)
Closed 6 years ago.
Why && operator of PostgreSQL 9.4 use for checking overlapping of two array, change the order of result?
I have a query
Select * FROM "View_Student_Plan" WHERE "ClassID" && ARRAY[53]:: bigint[]
My view is sorted in order of Admission date.
It works fine, if I use
Select * FROM "View_Student_Plan"
But when I attach remaining part with query it change the order of result.
I have used some other condition in where clause like Student_Name like 'P%', then it not affect order of result given by select statement. Then why don't for "ClassID" && ARRAY[53]:: bigint[]
In any RDBMS the order of the output is not set by default, and can be sorted differently every time! It can be sorted by indexes, the optimizer, default set up and ETC..
The only way of forcing a specific order(E.G. by Admission date) , is by using the ORDER BY clause .
EDIT: Regarding to your comment, a VIEW can't contain an ORDER BY clause, it is not effective as this clause should be at the end of the query , otherwise , it can be ignored.
E.G.
SELECT * FROM YourView
ORDER BY....--THIS WILL WORK
When it's inside the view its like:
SELECT *
FROM (SELECT * FROM ....
ORDER BY ..)
So the optimizer is free to ignore this.

PostgreSQL ORDER BY clause on numerical portion of text column [duplicate]

This question already has answers here:
SQL multiple column ordering
(9 answers)
PostgreSQL ORDER BY issue - natural sort
(9 answers)
Closed 7 years ago.
I have a table that has a column as primary key and the values are
G1,G2,G3,...Gn
I would like to order the data but the problem is when I use the ORDER BY clause it displays data as:
G1,G10,G11... G2,G20,G21, ... G3,G30,G31....
The query I use is:
select * from myTable order by id asc;
Your id column is obviously of some text data type so the ordering is alphabetical, not by the number. To get it to work, strip the 'G' from the id column when ordering:
SELECT * FROM mytable
ORDER BY right(id, -1)::integer;

In sql server why cant we use functions when comparing data from two tables [duplicate]

This question already has answers here:
Sql Server : How to use an aggregate function like MAX in a WHERE clause
(6 answers)
Closed 7 years ago.
can someone please tell me what is wrong with the following query
select 1
from table1 a,
table2 b
where a.pdate=max(b.pdate)
It is not compiled.
the other way to write this query is
set #pdate=pdate from table2
select 1
from table1 a,
table2 b
where a.pdate=max(b.pdate)
But I want to understand what is wrong with the first query.
Thanks
But I want to understand what is wrong with the first query.
The error message tells you something that could be of value to you.
An aggregate may not appear in the WHERE clause unless it is in a
subquery contained in a HAVING clause or a select list, and the column
being aggregated is an outer reference.
The max() function is an aggregate that returns the max value for a set of rows. The where clause is used to filter rows. So if you use an aggregate in the place where you are doing the filtering it is not clear what rows you actually want the max value for.
A rewrite could look like this:
select 1
from dbo.table1 as a
where a.pdate = (
select max(b.pdate)
from dbo.table2 as b
);
even second query is wrong.
Correct way,
Select #pdate=max(pdate) from table2
select 1
from table1 a where a.pdate=#pdate
or,
select 1
from table1 a where a.pdate=(Select max(pdate) from table2)
if you mention another column name apart from aggregate column then you hv to use group by

really simple SQL Not a GROUP BY expression - Oracle [duplicate]

This question already has answers here:
ORA-00979 not a group by expression
(10 answers)
Closed 5 years ago.
I tried to read about not a group by expression errors from some other posts, but all of them mention group functions such as MAX, MIN, etc. I'm not using any of it and it's a really simple query returning this sort of error.
SELECT *
FROM ad_voarnet_atendimento_pista
WHERE is_closed = 0
GROUP BY prefixo
ORDER BY prefixo
What am I doing wrong here?
Edit:
The expected result is the same that MySQL would give me with this query. It would exclude every duplicated value of the column PREFIXO. I want only 1 record of each value in the mentioned column.
The error message is this:
[Err] ORA-00979: not a GROUP BY expression
The GROUP BY is not useful outside of the context of an aggregate function like MIN() MAX() SUM() COUNT(), except perhaps to deduplicate rows. Just remove it. If you are looking to deduplicate results, use DISTINCT instead. If you use DISTINCT, it won't be of much value unless you are more specific about the columns in the SELECT list, excluding the primary key column.
SELECT
DISTINCT *
FROM
AD_VOARNET_ATENDIMENTO_PISTA
WHERE IS_CLOSED = 0
ORDER BY PREFIXO
GROUP BY is sometimes confused with ORDER BY. You already have an ORDER BY PREFIX0,

difference between usage of having clause and where clause [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
SQL: What's the difference between HAVING and WHERE?
What is the difference between using having clause and where clause. Could any one explain in detail.
HAVING filters grouped elements,
WHERE filters ungrouped elements.
Example 1:
SELECT col1, col2 FROM table
WHERE col1 = #id
Example 2:
SELECT SUM(col1), col2 FROM table
GROUP BY col2
HAVING SUM(col1) > 10
Because the HAVING condition can only be applied in the second example AFTER the grouping has occurred, you could not rewrite it as a WHERE clause.
Example 3:
SELECT SUM(col1), col2 FROM table
WHERE col1 = #id
GROUP BY col2
HAVING SUM(col1) > 10
demonstrates how you might use both WHERE and HAVING together:
The table data is first filtered by col1 = #id
then the filtered data is grouped
then the grouped data is filtered again by SUM(col1) > 10
WHERE filters rows before they are grouped in GROUP BY clause
while HAVING filters the aggregate values after GROUP BY takes place
HAVING specifies a search for something used in the SELECT statement.
In other words.
HAVING applies to groups.
WHERE applies to rows.
Without a GROUP BY, there is no difference (but HAVING looks strange then)
With a GROUP BY
HAVING is for testing condition on the aggregate (MAX, SUM, COUNT etc)
HAVING column = 1 is the same as WHERE column = 1 (no aggregate on column )
WHERE COUNT(*) = 1 is not allowed.
HAVING COUNT(*) = 1 is allowed
Having is for use with an aggregate such as Sum. Where is for all other cases.
They specify a search condition for a group or an aggregate. But the difference is that HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query whereas WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.
As other already said, having is used with group by. The reason is the order of execution - where is executed before group by, having is executed after it
Think of it as a matter of where the filtering happens.
When you specify a where clause you filter input rows to your aggregate function (ie: I only want to get the average age on persons living in a specific city.) When you specify a having constraint you specify that you only want a certain subset of the averages. (I only want to see cities with an average age of 70 years or above.)
Having is for aggregate functions, e.g.
SELECT *
FROM foo
GROUP BY baz
HAVING COUNT(*) > 8