0

I have some very basic SQL here:

SELECT TOP 1 *
  FROM  (SELECT TOP 8 *
        FROM [BP_BasicPolicy ] 
        )

For some reason it does not compile and I get the error:

Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ')'.

What is the correct syntax? I don't understand why I'm getting this error as I thought it was perfectly legitimate SQL Server syntax

4
  • What database do you use? Commented Jul 28, 2014 at 12:57
  • add an alias name after the final closing bracket? Commented Jul 28, 2014 at 12:57
  • 4
    TOP without ORDER BY is a) meaningless, and b) not allowed in a subquery. What are you attempting to do? Commented Jul 28, 2014 at 12:59
  • 2
    Why do you even need the nested tops? If you only want 1 record why wouldn't SELECT top 1 * FROM [BP_BasicPolicy] ORDER BY something work? Commented Jul 28, 2014 at 13:04

2 Answers 2

6

You need an alias for the subquery:

SELECT TOP 1 t.*
FROM (SELECT TOP 8 *
      FROM [BP_BasicPolicy ] 
     ) t

EDIT:

I hesitated to add, that using top without order by doesn't make sense. You need some ordering. So, you can do:

SELECT TOP 1 t.*
FROM (SELECT TOP 8 *
      FROM [BP_BasicPolicy ] 
      ORDER BY col1 ASC
     ) t
ORDER BY col2 DESC;

Actually, you don't need the order by at the outermost level, but it is still a good idea.

Without the order by, you might as well do:

SELECT TOP 1 t.*
FROM [BP_BasicPolicy ] ;

This will choose an arbitrary row. For a specific one, use order by.

Sign up to request clarification or add additional context in comments.

6 Comments

It'll still complain about the TOP without ORDER BY in the subquery.
@Damien_The_Unbeliever on SQL Server? I've never had a problem with it on 2008, 2012, 2014.
@JChao - I was misremembering which way around the error is reported. It'll definitely complain about ORDER BY without TOP, but this way around, it is of course just completely non-deterministic.
@Damien_The_Unbeliever -- why would it complain about not using the TOP keyword? Using ORDER BY without TOP is very common. I agree with your conclusion, but that part of your comment confused me.
@MJB - in the outer query, where ORDER BY defines the order of results, sure, but in a subquery, ORDER BY is only useful to actually define the meaning of TOP (or for generating XML) so ORDER BY in a subquery without TOP or FOR XML generates an error.
|
0

your query can be simplified as below, however if your intention isnt like that, please specify the objective, cheer :)

SELECT TOP 1 *  FROM [BP_BasicPolicy ] 

1 Comment

As many others have already pointed out...TOP with no ORDER BY is non-deterministic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.