where do I put the distinct in in my code? - sql

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;

Related

FROM keyword not found

I am getting an error, even though I actually do have the keyword!
Here's my code:
SELECT TOP(10) * FROM TABLE_NAME
Here's the error:
[42000][923] ORA-00923: FROM keyword not found where expected
What am I doing wrong?
Here is the right way of accessing top # rows
SELECT * FROM TABLE_NAME
WHERE ROWNUM <= 10
In general, you should not use top or limit or anything like that unless you are using order by. In Oracle, the traditional way to write your query is:
SELECT t.*
FROM TABLE_NAME
ORDER BY <something goes here>
WHERE rownum <= 10;
You can omit the ORDER BY, but then you will get an arbitrary set of 10 rows that might change from one call to another.

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;

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

TSQL Distinct, and OrderBy and WHERE

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.

Sequence within SQL Select

I'm having a bit of a problem with using my sequence within a SELECT statement.
SELECT
c.cust_name,
c.site,
customer_id_seq.nextval
FROM
customer c
WHERE
c.customer_id IS NULL
ORDER BY
c.site_code ASC
;
Is giving me an error:
00000 - "sequence number not allowed here"
*Cause: The specified sequence number (CURRVAL or NEXTVAL) is
inappropriate
here in the statement.
*Action: Remove the sequence number.
It's probably something obvious I'm doing wrong so hopefully this will be an easy answer.
You cannot use sequences in queries with ORDER BY.
Remove the ORDER BY or put in into a subquery:
SELECT q.*, customer_id_seq.nextval
FROM (
SELECT c.cust_name,
c.site
FROM customer c
WHERE c.customer_id IS NULL
ORDER BY
c.site_code ASC
) q
for IBM Imformix
In a SELECT statement, you cannot specify NEXTVAL or CURRVAL in the following contexts:
In the projection list when the DISTINCT keyword is used
In the WHERE, GROUP BY, or ORDER BY clauses
In a subquery
When the UNION operator combines SELECT statements
Why don't you use rownum instead of fetching values from sequence?