Monday, April 8, 2019

SQL Server : Some common and useful queries


Find all the employees and their department name

select emp_id,first_name,Last_Name,dept_id,dept_name
from employee e
inner join 
department d on e.department_id = d.DEPT_ID

we can also apply where clause to add filter for emp_id or first_name and find department and other details for specific employee.

Find all the employees who is not part of any department

select emp_id,first_name,Last_Name,dept_id,dept_name from employee e
left join department d on e.department_id = d.DEPT_ID

where e.department_id is null

Find no. of employees in each department and sum of their salary (i.e. total salary distributed for each department)

select count(emp_id) as empCount,sum(salary),department_id from employee

group by department_id

Find the no.of employee and department where salary distributed is greater than 100000

select count(emp_id) as empCount,sum(salary) as totalSalary, department_id from employee

group by department_id having sum(salary) >100000

ROW_NUMBER(), RANK(), DENSE_RANK()


SELECT  
--ROW_NUMBER() OVER (ORDER BY SALARY desc)AS RW_COUNTER,
 ROW_NUMBER() OVER ( PARTITION BY DEPARTMENT_ID ORDER BY SALARY desc)AS ROW_NUM,
EMP_ID,DEPARTMENT_ID,FIRST_NAME,SALARY 
FROM EMPLOYEE where salary is not null Order by DEPARTMENT_ID

SELECT  
--RANK() OVER (ORDER BY SALARY desc)AS RW_COUNTER,
RANK() OVER (PARTITION BY DEPARTMENT_ID ORDER BY SALARY desc)AS ROW_NUM,
EMP_ID,FIRST_NAME,SALARY ,DEPARTMENT_ID
FROM EMPLOYEE  where salary is not null Order by DEPARTMENT_ID

SELECT  --DENSE_RANK() OVER (ORDER BY SALARY desc)AS RW_COUNTER,
DENSE_RANK() OVER (PARTITION BY DEPARTMENT_ID ORDER BY SALARY desc)AS ROW_NUM,EMP_ID,FIRST_NAME,SALARY ,DEPARTMENT_ID
FROM EMPLOYEE where salary is not null and DEPARTMENT_ID IS NOT NULL
Order by DEPARTMENT_ID

Note: 
ROW_NUMBER will generate sequential row number based on given partition and order by columns.

RANK () will generate rank based on given partition and order by columns. for example :
if  you have given department_Id in partition and order by salary and lets consider that there are two employee who has same salary so for first employee rank would be 1 and second and third employee rank would be 2 and for fourth employee rank would be 4 as row count for 4th employee would be 4th.

DENSE_RANK() is same as rank but it will give rank 3rd for fourth employee instead of 4th.
i.e. rank assignment will not be depend on row number of particular result.
run above queries to see result.

Create Table :

CREATE TABLE [dbo].TEST (
    [Id] int IDENTITY(1,1) primary Key,
    [Name] nchar(50)  NOT NULL

);
creating table with primary key.

Primary key creation with clustered index :

ALTER TABLE [dbo].[Countries]
ADD CONSTRAINT [PK_Countries]
    PRIMARY KEY CLUSTERED ([CountryId] ASC);
GO

Renaming TABLE Column:

EXEC dbo.sp_rename @objname=N'[dbo].[Cities].[ref]', @newname=N're', @objtype=N'COLUMN'

Cursor Example :

ALTER PROCEDURE SP_TEST_DATETIME
 AS
 BEGIN

  DECLARE @WorkingStatrt DateTime
  DECLARE @WorkingEnd DateTime
  DECLARE @TempTime DateTime
  DECLARE @TotalTime datetime
  DECLARE @CaseKey int
  DECLARE @createTimeStamp datetime
  DECLARE @Action varchar(50)
  
DECLARE WorkingHorsCalculation CURSOR FOR
SELECT CASE_KEY,CREATE_TIMESTAMP,ACTION
FROM AUDIT_LOG_CASE 

-- Open cursor
OPEN WorkingHorsCalculation
-- Fetch data from cursor in to variable
FETCH NEXT FROM WorkingHorsCalculation
INTO @CaseKey,@createTimeStamp,@Action
WHILE @@FETCH_STATUS = 0
BEGIN
-- Do operation according to row value
if @Action='Working Case'
begin
PRINT @Action
SET @WorkingStatrt=@createTimeStamp;
PRINT @WorkingStatrt

end
-- Fetch the next cursor
FETCH NEXT FROM WorkingHorsCalculation
INTO @CaseKey,@createTimeStamp,@Action
END
-- Finally do not forget to close and deallocate the cursor
CLOSE WorkingHorsCalculation
DEALLOCATE WorkingHorsCalculation


END

--*******************************************************************----







Interview Questions and Answers on Exception handling in C#  ( Part-3 )

Question: Can we use try catch block inside of Catch block?
Answer: Yes.






Monday, November 12, 2018

Objects (Reference types) are also passed by value.


We will recall two concepts 'Call by Value' and 'Call by Reference' in context of a method call.

Call By Value : when we call a method by passing any value type, a copy of value type created inside of method so, any change to the variable's value inside the method, is local to that method, it will not change value of variable passed to that method. for example :

 Output :


In above example we saw, if we want to change value of  any 'value type' from another method we need to pass variable's reference to the method, otherwise all the changes to that variable will be local (inside) to that method.

Now, Question is about to 'Reference Type', Reference types are 'Passed by Value' or 'Passed by Reference' ?
You may not believe, if I will say reference types are also 'Passed by Value' because generally we saw when we pass any object to any method (say M1), any change to object inside M1() will reflect to caller. for example :



In the above example, after ChangeObject() method call, properties of Customer object has been changes. so, we can say objects are passed by reference.
No, It's not correct answer, objects are also 'Passed by Value'. See below example :




Monday, October 22, 2018

Linked List implementation in C#

  public class Node
    {
       public int item;
       public Node next;
       public Node(int it)
        {
            item = it;
            next = null;
            Console.Write("[{0}]-->", item);
        }
    }

    public class LinkedList
    {
       public Node top;

        public LinkedList(int item)
        {
            Node n = new Node(item);
            top = n;

        }

        public void Push(int item)
        {
            Node _node = new Node(item);

            //Add Node at before top
            if (top == null)
            {
                top = _node;
            }
            else
            {
                _node.next = top;
                top = _node;
            }
        }

        public void InsertAfter(Node node, int item)//Inserting item (new node) after given node.
        {
            Node newNode = new Node(item);
            if (top == null) return;
            Node nxtNode = top;
           
            while (nxtNode != null)
            {
                if (nxtNode.item == node.item)
                {
                    newNode.next = nxtNode.next;
                    nxtNode.next = newNode;
                    break;
                }
                else
                {
                    nxtNode = nxtNode.next;
                }
            }
        }

        public void Print()
        {
            if (top == null)
            {
                Console.WriteLine("List is empty");
                return;
            }
            Node nexNode =top;
            while (nexNode != null)
            {
                Console.WriteLine(nexNode.item);
                nexNode = nexNode.next;
            }

        }
    }
    class TestLinked
    {
        public static void Main()
        {
            LinkedList ll = new LinkedList(1);
            Console.WriteLine("Top item=" + ll.top.item); //each newly added item will be top of linked list.
            ll.Push(3);
            Console.WriteLine("Top item=" + ll.top.item);
            ll.Push(5);
            Console.WriteLine("Top item=" + ll.top.item);
            ll.Push(6);
            Console.WriteLine("Top item=" + ll.top.item);

            ll.InsertAfter(new Node(3), 4);
            ll.Print();
            Console.ReadLine();
        }
    }

Sunday, October 21, 2018

Stack implementation in C#

Stack implementation in C#

public class Stack
    {
        readonly int  _capacity;
        int top;
        int[] _stack ;
        public int Top
        {
            get { return top; }
        }
        public Stack()
        {
            _capacity = 1000;
            top = -1;
        }
        public Stack( int capacity)
        {
            _capacity = capacity;
            _stack = new int[_capacity];
            top = -1;
        }
        public void Push(int item)
        {
            if (top < _capacity - 1)
            {
                _stack[top + 1] = item;
                top++;
            }
            else
            {
                Console.WriteLine("Stack is full");
            }
        }
        public int Pop()
        {
            int itemToReturn=-1;
            if (top == -1)
            {
                Console.WriteLine("Stack empty!!");
               
            }
            else
            {
                 itemToReturn= _stack[top];
                top--;
                
            }
            return itemToReturn;
        }
        public int Peek()
        {
            if (top != -1)
            {
                return _stack[top];
            }
            else
            {
                Console.Write("Stack is empty!!!");
                return -1;

            }

            
        }

    }

Test :


class StackTest
    {
        public static void Main()
        {
            Stack s = new Stack(5);

            Console.WriteLine("Stack top=" + s.Top);
            s.Push(1);
            s.Push(2);
            s.Push(3);
            s.Push(4);
            s.Push(5);
            s.Push(6);

            Console.WriteLine("Stack item "+ s.Pop() +"  top=" + s.Top);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
           
            // ************** Test 2 **************************
            s.Push(7);
            s.Push(8);
            s.Push(9);
            s.Push(10);
            s.Push(11);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
            Console.WriteLine("Stack item " + s.Pop() + "  top=" + s.Top);
            Console.Read();
        }

    }

Friday, October 5, 2018

Interview Questions and Answers on Exception handling in C#  ( Part-2 )

Question : Can we use 'return' keyword in catch and finally block?
Answer: Yes, we can use return keyword in catch block but not in finally block, see below example :


 

Interview Questions and Answers on C# Exception handling


Interview Questions and Answers on Exception handling in C#  ( Part-1 )

Question: Will the code written after catch block be executed?
Answer : Yes, code written after Catch block will be executed. see the below example :
Here I am trying to generate 'DivideByZero' Exception that will be handled by catch block
and it will print exception message then program will also execute Console.WriteLine() statement and print "Code after exception block".


 class Exception1
    {
        public static void Main()
        {
            CheckStatementAfterCatch();
            Console.ReadLine();
        }
        public static void CheckStatementAfterCatch()
        {
            int a = 8;
            int b = 0;
            try
            {
                int c = a / b;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("Code after exception block");
            
        }
    }

Question 2: What will be output if program generates an exception and we only have finally block in code?
Answer : Here we have two scenario:
1. Method caller is calling your method inside try..catch block : In this scenario code will be executed, it will generate exception from try block (but not throw to caller) then finally block will be executed and after that exception would be passed to caller, caller will handle that exception.



2. Method caller is not using any try..catch block: In this scenario your program will crash....no meaning of finally bock in code.









C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...