Creating Index on #temp tables

#Temp tables are much like SQL tables that are defined and stored in TempDB. Difference between them and a permanent table is they are not allowed to have foreign keys.
 
One of the feature of temp table (#temp) is that we can add a clustered or non clustered index. Also, #temp tables allow for the auto-generated columns (fields) to be created. This can help the optimizer when determining the number of records. Below is an example of creating both a clustered and non-clustered index on a temp table.
  1. -- creating temp table - #employees
  2. CREATE TABLE #Employees  
  3. (  
  4. ID INT IDENTITY(1,1),  
  5. EmployeeID INT,  
  6. EmployeeName VARCHAR(50)  
  7. )  

  8. INSERT INTO #Employees  
  9. (  
  10. EmployeeID,  
  11. EmployeeName  
  12. )  
  13. SELECT  
  14. EmployeeID = e.EmployeeID  
  15. ,EmployeeName = e.EmployeeName  
  16. FROM dbo.Employees e  
  17.   
  18. -- creating clustered index  
  19. CREATE CLUSTERED INDEX IDX_C_Employees_EmployeeID ON #Employees(EmployeeID) 
  20.  
  21. -- creating non-clustured index  
  22. CREATE INDEX IDX_Users_UserName ON #Employees(EmployeeName)