Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
ayossib
Starting Member
3 Posts |
Posted - 2013-06-27 : 09:20:55
|
I have a little confusion with something.what is the difference between these 2 sql queries:(!!!my goal was to get the min id and the first name!!!)SELECT id, firstNameFROM employeeWHERE id = (SELECT MIN(id) FROM employee)orSELECT min(id), firstNameFROM employee |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-06-27 : 09:45:17
|
first one gives you record(s) with min id value from the table employeesecond one is not syntactically correctperhaps you meantSELECT min(id), firstNameFROM employeegroup by firstname gives you minimum id value for each employeewhich gives------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
 |
|
ayossib
Starting Member
3 Posts |
Posted - 2013-06-27 : 09:55:21
|
why the second one is not syntactically correct?The SQL MIN() Syntax is not:SELECT MIN(column_name) FROM table_name?? |
 |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2013-06-27 : 10:30:44
|
quote: Originally posted by ayossib why the second one is not syntactically correct?The SQL MIN() Syntax is not:SELECT MIN(column_name) FROM table_name??
That is only part of the syntax. The other rule is that any column in your select list that is outside of an aggregate function (such as MIN in your example), must also be listed in the group by clause. So both of the following are correct:SELECT MIN(column_name) FROM table_name;SELECT MIN(column_name), another_column FROM table_name group by another_column But the following is NOT correct:SELECT MIN(column_name), another_column FROM table_name |
 |
|
ayossib
Starting Member
3 Posts |
Posted - 2013-06-27 : 10:35:32
|
Now it's clear.Thanks you all. |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-06-27 : 10:37:11
|
quote: Originally posted by ayossib why the second one is not syntactically correct?The SQL MIN() Syntax is not:SELECT MIN(column_name) FROM table_name??
sql min syntax is not wrongbut your second statement was SELECT min(id), firstNameFROM employeeyou cant simultaneously select a column and apply aggregate over other unless you group on the individual columnwhy not try compiling both?SELECT min(id), firstNameFROM employeewill give this errorcolumn firstName is invalid in select clause because its not contained in a aggregation or a GROUP BY clausewhereas this worksSELECT min(id), firstNameFROM employeegroup by firstname ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
 |
|
|
|
|