TSQL Distinct, and OrderBy and WHERE - sql

I have the following SQL statement sample:
SELECT DISTINCT [CommentNdx]
,[CommentsText]
,[DateTimeAdded]
FROM [dbo].[CommentTable]
ORDER BY [dbo].[CommentTable].DateTimeStart DESC
WHERE [CommentsText] = 'Hello World'
I keep getting the error Incorrect syntax near the keyword 'WHERE'. I know the syntax is incorrect but I'm not sure how this should be formatted. Any help is appreciated.
UPDATE:
My mistake, I meant date time start should be datetimeadded. Corrected syntax.
SELECT DISTINCT [TestCommentNdx]
,[TestID]
,[CommentsText]
,[DateTimeAdded]
,[OperatorNdx]
FROM [PTDB].[dbo].[TestsComments]
WHERE [TestID] = 1174411854
ORDER BY [PTDB].[dbo].[TestsComments].[DateTimeAdded] DESC
UPDATE 2:
Thanks much everyone, one last thing, would it make a difference if there were joins in the select statement? I have a really long query with joins and when I try to use DISTINCT, I get ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

The WHERE needs to come before the ORDER BY. Also, you won't be able to sort by DateTimeStart unless it's included in the SELECT statement.

SELECT DISTINCT [CommentNdx]
,[CommentsText]
,[DateTimeAdded]
FROM [dbo].[CommentTable]
WHERE [CommentsText] = 'Hello World'
ORDER BY [dbo].[CommentTable].DateTimeStart DESC -- you can't do this
ORDER BY follows the WHERE clause.
EDIT: As per #LukeGirvin post, you can't sort by a column that isn't included in the SELECT clause.

Related

What is SQL's Keyword order? (Postgresql)

Depending on where you put SELECT, FROM, WHERE, etc, I have run into syntax errors. What is the proper order to write queries and code? An example below:
//No error
SELECT count(*)
FROM us_counties_pop_est_2019
WHERE births_2019 - deaths_2019 <=0;
vs
//Syntax error
SELECT count(*)
WHERE births_2019 - deaths_2019 <=0
FROM us_counties_pop_est_2019;
The main clauses of a SELECT statement in PostgreSQL are written in the following order:
[WITH]
SELECT
FROM
JOIN
WHERE
GROUP BY
HAVING
WINDOW
ORDER BY
OFFSET
LIMIT
If the query includes CTEs, then the WITH clause comes before the other ones.

SQL GROUP BY 1 2 3 and SQL Order of Execution

This may be a dumb question but I am really confused. So according to the SQL Query Order of Execution, the GROUP BY clause will be executed before the SELECT clause. However it allows to do something like:
SELECT field_1, SUM(field_2) FROM myTable GROUP BY 1
My confusion is that if GROUP BY clause happens before SELECT, in this scenario I provided, how does SQL know what 1 is? It works with ORDER BY clause and it makes sense to me because ORDER BY clause happens after SELECT.
Can someone help me out? Thanks in advance!
https://www.periscopedata.com/blog/sql-query-order-of-operations
My understanding is because it's ordinal notation and for the SELECT statement to pass syntax validation you have to have at least selected a column. So the 1 is stating the first column in the select statement since it knows you have a column selected.
EDIT:
I see people saying you can't use ordinal notation and they are right if you're using SQL Server. You can use it in MySQL though.
select a,b,c from emp group by 1,2,3. First it will group by column a then b and c. It works based on the column after the select statement.
Each GROUP BY expression must contain at least one column that is not an outer reference. You cannot group by 1 if it is not a column in your table.

SQL Apache Derby - Select last value in column

I am using Apache Derby and am trying to select the last value in a column.
Currently I have the following:
SELECT id FROM hotels ORDER BY id DESC WHERE ROWNUM <=1;
However this is resulting in a syntax error:
Syntax error: Encountered "WHERE" at line 1, column 44.
Would anyone know the proper way to write this query?
Thank you.
The order by clause goes after the where. Perhaps you intend:
SELECT MAX(id)
FROM hotels;

where do I put the distinct in in my code?

I have the following sql code:
select upper(regexp_substr(street1, '\S+$'))
but I don't know where I should put the distinct keyword to have unique values in the table, because I prints out many duplicate values.
Edit - from comments below.
Complete Query(error):
select distinct UPPER(REGEXP_SUBSTR(STREET1, '\S+$'))
from HELENS_DATA
order by REGEXP_SUBSTR(STREET1, '\S+$') asc
Error Message:
ORA-01791: not a SELECTed expression 01791. 00000 - "not a SELECTed expression" *Cause: *Action: Error at Line: 3 Column: 24
Complete Query(works):
select distinct UPPER(REGEXP_SUBSTR(STREET1, '\S+$'))
from HELENS_DATA
order by UPPER(REGEXP_SUBSTR(STREET1, '\S+$')) desc;
please NOTE that the initial query tried to change the query values to upper by using UPPer() function how ever I have mistakenly ignored the function in the ORDER BY clause and it was not the fault of 'DISTINCT'.
distinct always comes right after select:
select distinct upper...
It's interesting that DISTINCT fails when you have the UPPER function in place. You can try to get around it using a subquery:
SELECT DISTINCT Ending
FROM (select upper(regexp_substr(street1, '\S+$')) Ending) A
The subquery really shouldn't be necessary though, this should work too, as chue x recommended.
SELECT DISTINCT upper(regexp_substr(street1, '\S+$'))
Have you tried:
SELECT DISTINCT upper(...) AS 'Field Name'
If you name the field that you are performing this to that may work and allow you to use DISTINCT.
To Finalise:
Initially I have run the code in the oracle database as the following code
Complete Query(error):
select distinct UPPER(REGEXP_SUBSTR(STREET1, '\S+$'))
from HELENS_DATA
order by REGEXP_SUBSTR(STREET1, '\S+$') asc;
And as a result I have received the following error message:
ORA-01791: not a SELECTed expression 01791. 00000 - "not a SELECTed expression"
*Cause: *Action: Error at Line: 3 Column: 24
The answers above helped me to find out the mistake that I have overlooked and the following code is the completed SQL Query which is working fine.
Complete Query(works):
select distinct UPPER(REGEXP_SUBSTR(STREET1, '\S+$'))
from HELENS_DATA
order by UPPER(REGEXP_SUBSTR(STREET1, '\S+$')) desc;
please NOTE that the initial query tried to change the query values to upper by using UPPer() function how ever I have mistakenly ignored the function in the ORDER BY clause and it was not the fault of 'DISTINCT'.
Conlusion is that whatever argument the SELECT clause has, the other potential clauses, e.g. WHERE, ORDER BY ... etc. should also have the same pattern or same value.
Thanks to everyone.
You don't have to repeat the code in the ORDER BY clause. Whatever alias you define in the SELECT list, can be used in the ORDER BY:
SELECT DISTINCT
UPPER(REGEXP_SUBSTR(street1, '\S+$')) AS street1_upper
FROM
HELENS_DATA
ORDER BY
street1_upper DESC;

Using the DISTINCT keyword causes this error: not a SELECTed expression

I have a query that looks something like this:
SELECT DISTINCT share.rooms
FROM Shares share
left join share.rooms.buildingAdditions.buildings.buildingInfoses as bi
... //where clause omitted
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent
Which results in the following exception:
Caused by: org.hibernate.exception.SQLGrammarException: ORA-01791: not a SELECTed expression
If I remove the DISTINCT keyword, the query runs without issue. If I remove the order by clause, the query runs without issue. Unfortunately, I can't seem to get the ordered result set without duplicates.
You are trying to order your result with columns that are not being calculated. This wouldn't be a problem if you didn't have the DISTINCT there, but since your query is basically grouping only by share.rooms column, how can it order that result set with other columns that can have multiple values for the same share.rooms one?
This post is a little old but one thing I did to get around this error is wrap the query and just apply the order by on the outside like so.
SELECT COL
FROM (
SELECT DISTINCT COL, ORDER_BY_COL
FROM TABLE
// ADD JOINS, WHERE CLAUSES, ETC.
)
ORDER BY ORDER_BY_COL;
Hope this helps :)
When using DISTINCT in a query that has an ORDER BY you must select all the columns you've used in the ORDER BY statement:
SELECT DISTINCT share.rooms.floors.floorOrder, share.rooms.roomNumber,
share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent
...
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent