1

I want to get the count of all the columns that are retrieved in the query.I have used the below code:

select count (*) 
from ( 
   select distinct ID,salary,name,location 
   from test 
) ;

I am getting an error message:

Incorrect error at ; expecting AS,ID or quoted_ID

When I add as below:

select count (*) 
from (
   select distinct ID,salary,name,location 
   from test 
) as count;

The query works now but the column name is not renamed to the alias given. What is the logic behind this?

4
  • Some DBMS require derived tables to have an alias, some don't. Which DBMS are you using? Commented Apr 17, 2017 at 20:57
  • I am using Microsoft SQL Server 08,My concern is even after giving the alias name the column name is not changed,it is displayed as No column name. Commented Apr 17, 2017 at 21:27
  • You gave the derived table an alias, not the column. If you want to give the column an alias you have to specify it there, count(*) as count from (...) as x Commented Apr 18, 2017 at 6:05
  • this makes sense now.Thanks a_horse_with_no_name Commented Apr 18, 2017 at 6:32

3 Answers 3

1

In Sql you have to give alias to subquery. So that's the reason the second query works and first one fails

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

1 Comment

The second query works but the column name is not renamed with the alias name given in query,it is displayed as "no column name"
1

i don't know what you are trying to achieve but to correct this would be

select count (*) from (select distinct ID,salary,name,location from test ) as myTAble; 

subquery will act as your table to query from therefore it needs a name or alias

2 Comments

Alias name should be used just after the column which is supposed to be renamed that is before "from" .Anyhow in this code,the column name is displayed without the alias name
will to put it officially a derived table needs to have a name as far as i know
1

You are giving alias to the table and not column. The following query would work.

select count (*) As count
    from (
       select distinct ID,salary,name,location 
       from test 
    ) as tbl;

Comments

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.