Query to find manager of employee in sql

We have Employees Table.

Write a SQL query to display employee name along with Manager name.


To achieve this we have to use self join

SELECT a.employee_id,a.first_name,b.employee_id manager_id,b.first_name manager
FROM employees a
JOIN employees b
ON a.manager_id=b.employee_id;

Output:

Sorting ArrayList element using Comparable

How to sort User define object ?


Let’s say we have Employee Object and we want sort based on Employee id Then we have to use Comparable Interface of java.util package.

Comparable Interface


This interface imposes a total ordering on the objects of each class that implements it.
This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort).

Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C.

Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

Sorting Arraylist Object

Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.spy.Employee.Arraylist;
 
public class Employee implements Comparable<Employee>
{
 
	int id;
	String name;
 
	public Employee(int id,String name) 
	{
 
		this.id=id;
		this.name=name;
 
	}
	public int getId() 
	{
		return id;
	}
 
	public void setId(int id) 
	{
		this.id = id;
	}
 
	public String getName() 
	{
		return name;
	}
 
	public void setName(String name) 
	{
		this.name = name;
	}
 
	@Override
	public int compareTo(Employee e) 
	{
 
		int emp_id =((Employee)e).getId();
 
		return this.id-emp_id;
	}
 
	@Override
	public String toString() 
	{
		return "Employee [id=" + id + ", name=" + name + "]";
	}
 
}

ArrayList_emp.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.spy.Employee.Arraylist;
 
import java.util.ArrayList;
import java.util.Collections;
 
public class ArrayList_emp 
{
 
	public static void main(String[] args) 
	{
 
 
		ArrayList<Employee> emp_list=new ArrayList<Employee>();
 
 
		emp_list.add(new Employee(2,"Bhavesh"));
		emp_list.add(new Employee(3,"Sahil"));
		emp_list.add(new Employee(1,"Nilay"));
 
 
		Collections.sort(emp_list);
		for (Employee emp : emp_list) 
		{
 
			System.out.println("Employee id: "+emp.getId());
			System.out.println("Employee name: "+emp.getName());
			System.out.println("**********************");
 
		}	
	}	
}

Output: