ON keyword is used in case of join. in join it returns all data which will meet that condition but which record not meet that condition than it show null in particular field.
We have this sample data in the Department table:
DeptId DeptName
----------- ---------------
1 HR
2 Payroll
3 Admin
4 Marketing
5 HR & Accounts
And here is the sample data for the Employees table:
EmpId EmpName DeptId EmpSalary
----------- --------------- ----------- ---------------------
1 John 1 5000.00
2 Albert 1 4500.00
3 Crain 2 6000.00
4 Micheal 2 5000.00
5 David NULL 34.00
6 Kelly NULL 457.00
7 Rudy 1 879.00
8 Smith 2 7878.00
9 Karsen 5 878.00
10 Stringer 5 345.00
11 Cheryl NULL NULL
Let’s say we are asked to show the list of all employees and the department name of only those employees who have “HR” or “HR & Accounts” department; then we would write a query like this:
select * from employees e
left join departments d on e.deptid = d.deptid
and ( d.deptname = 'HR' or d.deptname = 'HR & Accounts')
and the result of this query is:
EmpId EmpName DeptId EmpSalary DeptId DeptName
----------- --------------- ----------- --------------------- ----------- ---------------
1 John 1 5000.00 1 HR
2 Albert 1 4500.00 1 HR
3 Crain 2 6000.00 NULL NULL
4 Micheal 2 5000.00 NULL NULL
5 David NULL 34.00 NULL NULL
6 Kelly NULL 457.00 NULL NULL
7 Rudy 1 879.00 1 HR
8 Smith 2 7878.00 NULL NULL
9 Karsen 5 878.00 5 HR & Accounts
10 Stringer 5 345.00 5 HR & Accounts
11 Cheryl NULL NULL NULL NULL
if we are asked to show only those employees who have their department name “HR” or “HR & Accounts”? We would write a query like this:
select * from employees e
left join departments d on e.deptid = d.deptid
where ( d.deptname in ('HR','HR & Accounts'))
and the result of this query is:
Collapse | Copy Code
EmpId EmpName DeptId EmpSalary DeptId DeptName
----------- --------------- ----------- --------------------- ----------- ---------------
1 John 1 5000.00 1 HR
2 Albert 1 4500.00 1 HR
7 Rudy 1 879.00 1 HR
9 Karsen 5 878.00 5 HR & Accounts
10 Stringer 5 345.00 5 HR & Accounts
you can write your query by using in query
select * from urTableName where rollNo in (select top 10 rollNo from urSecondTable order by rollNo).
i think it will solve your problem.