Wednesday 25 December 2013

Interview Questions on web farm and web garden in Dot Net


Web Garden- Web application deployed on a server with multiple processors.
Web Farm- Web application deployed on multiple server.

Q : What is the difference between a web farm and a web garden?
Ans :Web Farm :-After developing our  web application we host it on IIS Server.  Now one standalone server is sufficient to process ASP.NET Request and response for a small web sites but when the site comes for big organization where there an millions of daily user hits then we need to host the sites on multiple Server. This is called web farms. Where single site hosted on multiple IIS Server and they are  running behind the Load Balancer.
Web Garden :-All IIS Request process by worker process ( w3wp.exe). By default each and every application pool contain single worker process. But An application pool with multiple worker process is called Web Garden.   Many worker processes with same Application Pool can sometimes provide better throughput performance and application response time. And Each Worker Process Should have there own Thread and Own Memory space.

Q : How to configure our web garden?
Right Click on Application Pool > Properties > GoTo Performance Tab 
In bottom Group Section  Increase the Worker Process Count.

Q : What is the restriction in web garden?
There are some Certain Restriction to use Web Garden with your web application. If we use Session Mode to "in proc", our application will not work correctly because session will be handled by different Worker Process. For Avoid this Type of problem we should have to use Session Mode "out proc" and we can use "Session State Server" or "SQL-Server Session State".

Q : What are the implications on Application and Session state variables in a web farm or a web garden?
Ans : In both a Web garden and a Web farm, client requests are directed to the ASP.NET process that is currently least busy. That means that a single client can interact with different CPUs or servers over the course of his or her session. This has the following implications for Application and Session state variables:
Q : Application state variables are unique to each separate instance of the Web application.
Ans :Clients can share information through Application state if the Web application is running on a Web garden or a Web farm.
Q : Session state variables are stored in-process by default.
Ans : To enable Session state in a Web garden or Web farm, you need to specify a Session state provider.
Q : How can you share Application State in a web farm or a web garden?
Ans : To share data across multiple sessions in a Web garden or Web farm, you must save and restore the information using a resource that is available to all the processes. This can be done through an XML file, a database, or some other resource using the standard file or database access methods.
Q : What are the two built-in ways provided by ASP.NET to share Session state information across a Web garden or Web farm?
Ans : ASP.NET provides two built-in ways to share Session state information across a Web garden or Web farm. You can share Session state using:

A state server, as specified by a network location
This technique is simple to implement and doesn’t require you to install Microsoft SQL Server.
A SQL database, as specified by a SQL connection
This technique provides the best performance for storing and retrieving state information.
Q : What are the steps to follow to share Session state information using a state server?
Ans : To share Session state information using a state server, follow these steps:
1. In the Web application’s Web.config file, set the sessionState element’s mode and stateConnectionString attributes.
2. Run the aspnet_state.exe utility on the Session state server. The aspnet_state.exe utility is installed in the \WINDOWS\Microsoft.NET \Framework\version folder when you install Visual Studio .NET Professional or Visual Studio .NET Enterprise Architect editions.
Q : What are the steps to follow to share Session state information using a SQL database?
Ans :To share Session state information using a SQL database, follow these steps:
1. In the Web application’s Web.config file, set the sessionState element’s mode and sqlConnectionString attributes.
2. Run the InstallSqlState.sql utility on the Session state server. This utility installs the SQL database that shares Session state information across processes. The InstallSqlState.sql utility is installed in the \WINDOWS\Microsoft.NET \Framework\version folder when you install Visual Studio .NET Professional, Visual Studio .NET Enterprise Developer, or Visual Studio .NET Enterprise Architect editions.

Q : What does the term Scalability mean?
Ans :scalability is the ability of a system, network, or process to handle a growing amount of work in a capable manner or its ability to be enlarged to accommodate that growth.For example, it can refer to the capability of a system to increase total throughput under an increased load when resources (typically hardware) are added. ASP.NET Web applications support this concept through their ability to run in multiple processes and to have those processes distributed across multiple CPUs and/or multiple servers.

Type of session in Dot net

How many types of Session :-


Priviously we discussed  about Session and session interview question We will talk about types of session.
Types of session

  1. In-process session
  2. Out process session / State server session
  3. Sql server session 
  4. Off session mode 
  5. Custom session mode 

In process Session mode

When the session state mode set to inProc :-The session state variable are stored on the web server memory inside the asp.net worker process.This is default session state mode.
It is very helpful small website or where number of user very less.we should avoid InProc in "web garden".

Web Garden- Web application deployed on a server with multiple processors.
Web Farm- Web application deployed on multiple server.
For detail of "Web garden" and "web farm" click here

  1. Off - Disables session state for entire web application 
  2. Inproc - 
      Fig(1)

      Fig(2)

    Fig(3)
Video for Inproc session mode in Dot Net
 Now the behind the web Form 1(Fig -1) coding will (coding for sending the data from one web  form to another web form)

Protected void btnsenddata_Click( Object sender , Event args e)
{
      Session ["name"] = textbox1.text;
      Session ["Email"] = textbox2.text;
Response.redirect("webform2.aspx");

}

Now the behind the web Form 1(Fig -1)
Protected void Page_Load( Object sender , Event args e)
{    
     if(Session ["name"] ! = null)
{
      lable1.text = Session ["name"].ToString();
}
  
     if(Session ["Email"] ! = null)
 {
     lable2.text = Session ["Email"] .ToString();

}
}

After this we have to set in web Config file
<Configuration>
<system.web>
<sessionState mode = "Inproc" timeout = "20"
</sessionstate>

For More Detail Watch Above video...

Note - If we set session state mode as "Off" then Disables session state for entire web application.



Advantages Disadvantages
Easy to implement, all time it require is, to set, The session state mod=inproc
in web config file.
Session state data is lost when the worker process or application pool is recycled 
It is best because the session state memory rept on the web server with in the Asp.net worker process.Not suitable for webform & webgarden.
Suitable for web application hosted on a single server.,,
Object can be added without serialization.
Scalability could be on an issue. 

Out process/ State server Session mode



  • State server uses a stand alone window services which is independent of IIS and can also be run on separate server.
  • This session state is totally managed by Asp.net-state.exe.
  • This server may run on the same system, But its outside of the main application domain where your web application is running. This means if you restart your application process your session data will be alive.
  • This has many disadvantages due the overhead of the serialization & De-serialization involved. it also increase the cost of the data access because every time the user retrieves session data.  



 Now the behind the web Form 1(Fig -1) coding will (coding for sending the data from one web  form to another web form)

Protected void btnsenddata_Click( Object sender , Event args e)
{
      Session ["name"] = textbox1.text;
      Session ["Email"] = textbox2.text;
Response.redirect("webform2.aspx");

}

Now the behind the web Form 1(Fig -1)
Protected void Page_Load( Object sender , Event args e)
{    
     if(Session ["name"] ! = null)
{
      lable1.text = Session ["name"].ToString();
}
  
     if(Session ["Email"] ! = null)
 {
     lable2.text = Session ["Email"] .ToString();

}
}

After this we have to set in web Config file
<Configuration>
<system.web>
<sessionState mode = "StateServer"  StateconnectionString =" tcpip = localhost = ipaddress"
  timeout = "20"
</sessionstate>

For More Detail Watch Above video...


Sql server session 

When Should be used SQL Server session mode :-
  • SQL Server session mode is a more reliable & secure session state management.
  • It keeps data in a centralized location (database)
  • we should use SQL Server session mode when we need to implement session with more security.
  • If there happens to be frequent server restarts, This is an ideal choice.
  • This is the perfect mode for web form and web garden security.
  • We can use SQL Server session mode when we need to share session  b/w two different application.





Protected void btnsenddata_Click( Object sender , Event args e)
{
      Session ["name"] = textbox1.text;
      Session ["Email"] = textbox2.text;
Response.redirect("webform2.aspx");

}

Now the behind the web Form 1(Fig -1)
Protected void Page_Load( Object sender , Event args e)
{    
     if(Session ["name"] ! = null)
{
      lable1.text = Session ["name"].ToString();
}
  
     if(Session ["Email"] ! = null)
 {
     lable2.text = Session ["Email"] .ToString();

}
}

After this we have to set in web Config file
<Configuration>
<system.web>
<sessionState mode = "SqlServer"  SqlConnectionString =" DataSource = ;integrated security  =SSPI"
  timeout = "20"
</sessionstate>

For More Detail Watch Above video...





Partial class in C#

Partial class is a new feature added to C# 2.0 and Visual Studio 2005. It is supported in .NET Framework 2.0. If you are working with .NET 1.0 or 1.1, partial classes may not work. 
It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.

When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.

When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio.

Benefit of partial classes:

1) More than one developer can simultaneously write the code for the class.

2) You can easily write your code (for extended functionality) for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.

There are a few things that you should be careful about when writing code for partial classes: 
  • All the partial definitions must proceeded with the key word "Partial".
  • All the partial types meant to be the part of same type must be defined within a same assembly and module.
  • Method signatures (return type, name of the method, and parameters) must be unique for the aggregated typed (which was defined partially).
  • The partial types must have the same accessibility.
  • If any part is sealed, the entire class is sealed.
  • If any part is abstract, the entire class is abstract.
  • Inheritance at any partial type applies to the entire class.
I have attached code of the partial classes along with this article. You can open the project and understand the functionality.

Hope the article would have helped you in understanding what partial classes are. Waiting for your feedback.
Example
//partial class


public partial class Student

{
public virtual void GetRollNo();
}

public partial class Student
{
public virtual void GetStudentName();
}

//Derived class

public class School : Student
{
public void getStudentDetails()
{
GetRollNo();
getStudentDetails(); 
}
}

Tuesday 24 December 2013

Delegate in C#

                                                                                                                                            Previous.....
                                                                                                                                                      Next....       Delegates

A delegate is a typesafe function pointer. delgate is pointing to function.
A Delegate is similar to a class. You can create an instance of it, and when you do so, you pass in the function name as a parameter to the delegate constructor, and it is to this function the delegate will point to.

A delegate is a function pointer delegate is a type safe function pointer. Actually a delegates points to the function when we invoke the delegate the function will be invoked.

Use of Delegate: Reason is because of the flexibilty we will get in this approach(Delegate)
30. What is the main use of delegates in C#?
Delegates are mainly used to define call back methods.

syntax of delegate is similar to the function.

Delegate can be used to point to a function which is similar signature. This delegate can point to any function that has got void return type & string parameter

How to make delegate point to a function to do that u have to create a instance of the delegate this is where a delegate is similar to a class.

And to the constructor of this delegate you pass in the name of the function to which you want this delegate to point.
the parameter must be a method name that method should have a void return type and string paramer.
Delegate is a type safe function pointer.That is, they hold reference(Pointer) to a function. 

The signature of the delegate must match the signature of the function, the delegate points to, otherwise you get a compiler error. This is the reason delegates are called as type safe function pointers.


Tip to remember delegate syntax: Delegates syntax look very much similar to a method with a delegate keyword.
-----------------------------------------------------------------------------------------

Some of the advantages of Delagates are:-

1.It encapsulates the method call
2.It increases the performance of the application
3.We can call a method Asynchronously using a delegate.We have multicast delegates as well..

There is a lot confusion around in developer community about the exact use of delegates. Here is what delegates are.

Delegate is a way to encapulate a method call as an object. This is very important to understand that when you create a delegate you are in essense creating an object that encapsulates a method call. Since you are wrapping a method call as an object, you can do things with delegates that are only possible with objects. you can store them, you can pass them as method parameters, you can invoke them (so that they invoke target methods) when timings and conditions are right.

just consider following statement

string str = obj.SomeMethod();

when CLR comes accross this statement, it will execute the targer method(obj.SomeMethod()). But what if I want to store this call to a method and invoke only if some conditions are met?? can i do

List<method> myMethods = new List<method>(); to store them?? NO!!!!

but this is possible with delegates.

here is a code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delegate1
{
    public delegate void HellowFunctionDelegate(string message);

    class Program
    {
        static void Main(string[] args)
        {
            HellowFunctionDelegate del = new HellowFunctionDelegate(Hellow);
            del("Hellow from Delegate");
            Console.ReadLine();
        }

        public static void Hellow(string message)
        {
            Console.WriteLine(message);
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delegate1
{
    public delegate void HellowFunctionDelegate(string message);

    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> emplist = new List<Employee>();
            emplist.Add(new Employee() { ID = 1, Name = "Sachin", Salary = 50000, Experience = 3 });
            emplist.Add(new Employee() { ID = 2, Name = "Yuvraj", Salary = 30000, Experience = 2 });
            emplist.Add(new Employee() { ID = 3, Name = "Rahul", Salary = 80000, Experience = 7 });
            emplist.Add(new Employee() { ID = 4, Name = "Kiran", Salary = 70000, Experience = 5 });


            IsPromotable isPromotable = new IsPromotable(Pramote);
            Employee.PromotEmployee(emplist, isPromotable);
Employee.PromotEmployee(emplist, emp => emp.Experience >= 5);        }
        public static bool Pramote(Employee e)
        {
            if (e.Experience >= 5)
            {
                return true;
            }
            else
            {
                return false;                    
            }
        }
    }

    delegate bool IsPromotable(Employee emp);

    class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public int Experience { get; set; }

        public static void PromotEmployee(List<Employee> employeeList, IsPromotable IsEligibleToPramote)
        {
            foreach (Employee e in employeeList)
            {
                if (IsEligibleToPramote(e))
                {
                    Console.WriteLine(e.Name + " Promoted");
                }
            }

        }

    }
}


  


                                                                                                                                            Previous.....                                                                                                                                                                                                                                                                                                                        Next....       




Monday 23 December 2013

Important SQL Query

                                                                                                                                                                                               Next.......

You can also get this Sql Query.. From this link.
http://a4academics.com/interview-questions/53-database-and-sql/397-top-100-database-sql-interview-questions-and-answers-examples-queries
Table Name : Employee
Employee Id First NameLast NameSalary Joining DateDepartment 
1JohnAbraham100000001-JAN-13 12.00.00 AMBanking 
2MichaelClarke80000001-JAN-13 12.00.00 AMInsurance
3Roy Thomas70000001-FEB-13-12.00.00 AMBanking 
4TomJose60000001-FEB-13-12.00.00 AMInsurance
5JerryPinto65000001-FEB-13-12.00.00 AMInsurance
6PhilipMathew75000001-JAN-13 12.00.00 AMServices
7Test Name 112365000001-JAN-13 12.00.00 AMServices
8Test Name 2Lname%60000001-FEB-13-12.00.00 AMInsurance

Table Name : Incentives

Incentives Ref ID Incentives Date Incentives Amount 
101-FEB-135000
201-FEB-133000
301-FEB-134000
101-JAN-13 4500
201-JAN-13 3500

SQL Queries Interview Questions and Answers on "SQL Select" - Examples


1. Get all employee details from the employee table

Select * from employee

2. Get First_Name,Last_Name from employee table

 Select first_name, Last_Name from employee

3. Get First_Name from employee table using alias name “Employee Name”

 Select first_name Employee Name from employee

4. Get First_Name from employee table in upper case

 Select upper(FIRST_NAME) from EMPLOYEE

5. Get First_Name from employee table in lower case

Select lower(FIRST_NAME) from EMPLOYEE

6. Get unique DEPARTMENT from employee table

select distinct DEPARTMENT from EMPLOYEE

7. Select first 3 characters of FIRST_NAME from EMPLOYEE

Oracle Equivalent of SQL Server SUBSTRING is SUBSTR, Query : select substr(FIRST_NAME,0,3) from employee

SQL Server Equivalent of Oracle SUBSTR is SUBSTRING, Query : select substring(FIRST_NAME,0,3) from employee

MySQL Server Equivalent of Oracle SUBSTR is SUBSTRING. In MySQL start position is 1, Query : select substring(FIRST_NAME,1,3) from employee

8. Get position of 'o' in name 'John' from employee table

Oracle Equivalent of SQL Server CHARINDEX is INSTR, Query : Select instr(FIRST_NAME,'o') from employee where first_name = 'John'

SQL Server Equivalent of Oracle INSTR is CHARINDEX, Query: Select CHARINDEX('o',FIRST_NAME,0) from employee where first_name = 'John'

MySQL Server Equivalent of Oracle INSTR is LOCATE, Query: Select LOCATE('o',FIRST_NAME) from employee where first_name = 'John'

9. Get FIRST_NAME from employee table after removing white spaces from right side

select RTRIM(FIRST_NAME) from employee

10. Get FIRST_NAME from employee table after removing white spaces from left side

select LTRIM(FIRST_NAME) from employee

11. Get length of FIRST_NAME from employee table

Oracle,MYSQL Equivalent of SQL Server Len is Length , Query :select length(FIRST_NAME) from employee

SQL Server Equivalent of Oracle,MYSQL Length is Len, Query :select len(FIRST_NAME) from employee

12. Get First_Name from employee table after replacing 'o' with '$'

select REPLACE(FIRST_NAME,'o','$') from employee

13. Get First_Name and Last_Name as single column from employee table separated by a '_'

Oracle Equivalent of MySQL concat is '||', Query : Select FIRST_NAME|| '_' ||LAST_NAME from EMPLOYEE

SQL Server Equivalent of MySQL concat is '+', Query : Select FIRST_NAME + '_' +LAST_NAME from EMPLOYEE

MySQL Equivalent of Oracle '||' is concat, Query : Select concat(FIRST_NAME,'_',LAST_NAME) from EMPLOYEE

14. Get FIRST_NAME ,Joining year,Joining Month and Joining Date from employee table

SQL Queries in Oracle, Select FIRST_NAME, to_char(joining_date,'YYYY') JoinYear , to_char(joining_date,'Mon'), to_char(joining_date,'dd') from EMPLOYEE

SQL Queries in SQL Server, select SUBSTRING (convert(varchar,joining_date,103),7,4) , SUBSTRING (convert(varchar,joining_date,100),1,3) , SUBSTRING (convert(varchar,joining_date,100),5,2) from EMPLOYEE

SQL Queries in MySQL, select year(joining_date),month(joining_date), DAY(joining_date) from EMPLOYEE


Database SQL Queries Interview Questions and answers on "SQL Order By"

15. Get all employee details from the employee table order by First_Name Ascending

Select * from employee order by FIRST_NAME asc

16. Get all employee details from the employee table order by First_Name descending

Select * from employee order by FIRST_NAME desc

17. Get all employee details from the employee table order by First_Name Ascending and Salary descending

Select * from employee order by FIRST_NAME asc,SALARY desc

SQL Queries Interview Questions and Answers on "SQL Where Condition" - Examples

18. Get employee details from employee table whose employee name is “John”

Select * from EMPLOYEE where FIRST_NAME = 'John'

19. Get employee details from employee table whose employee name are “John” and “Roy”

Select * from EMPLOYEE where FIRST_NAME in ('John','Roy')

20. Get employee details from employee table whose employee name are not “John” and “Roy”

Select * from EMPLOYEE where FIRST_NAME not in ('John','Roy')

SQL Queries Interview Questions and Answers on "SQL Wild Card Search" - Examples

21. Get employee details from employee table whose first name starts with 'J'

Select * from EMPLOYEE where FIRST_NAME like 'J%'

22. Get employee details from employee table whose first name contains 'o'

Select * from EMPLOYEE where FIRST_NAME like '%o%'

23. Get employee details from employee table whose first name ends with 'n'

Select * from EMPLOYEE where FIRST_NAME like '%n'

SQL Queries Interview Questions and Answers on "SQL Pattern Matching" - Examples

24. Get employee details from employee table whose first name ends with 'n' and name contains 4 letters

Select * from EMPLOYEE where FIRST_NAME like '___n' (Underscores)

25. Get employee details from employee table whose first name starts with 'J' and name contains 4 letters

Select * from EMPLOYEE where FIRST_NAME like 'J___' (Underscores)

26. Get employee details from employee table whose Salary greater than 600000

Select * from EMPLOYEE where Salary > 600000

27. Get employee details from employee table whose Salary less than 800000

Select * from EMPLOYEE where Salary < 800000

28. Get employee details from employee table whose Salary between 500000 and 800000

Select * from EMPLOYEE where Salary between 500000 and 800000

29. Get employee details from employee table whose name is 'John' and 'Michael'

Select * from EMPLOYEE where FIRST_NAME in ('John','Michael')


SQL Queries Interview Questions and Answers on "SQL DATE Functions" - Examples

30. Get employee details from employee table whose joining year is “2013”

SQL Queries in Oracle, Select * from EMPLOYEE where to_char(joining_date,'YYYY') = '2013'

SQL Queries in SQL Server, Select * from EMPLOYEE where SUBSTRING(convert(varchar,joining_date,103),7,4) = '2013'

SQL Queries in MySQL, Select * from EMPLOYEE where year(joining_date) = '2013'

31. Get employee details from employee table whose joining month is “January”

SQL Queries in Oracle, Select * from EMPLOYEE where to_char(joining_date,'MM') = '01' or Select * from EMPLOYEE where to_char(joining_date,'Mon') = 'Jan'

SQL Queries in SQL Server, Select * from EMPLOYEE where SUBSTRING(convert(varchar,joining_date,100),1,3) = 'Jan'

SQL Queries in MySQL, Select * from EMPLOYEE where month(joining_date) = '01'

32. Get employee details from employee table who joined before January 1st 2013

SQL Queries in Oracle, Select * from EMPLOYEE where JOINING_DATE < to_date('01/01/2013','dd/mm/yyyy')

SQL Queries in SQL Server (Format - “MM/DD/YYYY”), Select * from EMPLOYEE where joining_date < '01/01/2013'

SQL Queries in MySQL (Format - “YYYY-DD-MM”), Select * from EMPLOYEE where joining_date < '2013-01-01'

33. Get employee details from employee table who joined after January 31st

SQL Queries in Oracle, Select * from EMPLOYEE where JOINING_DATE > to_date('31/01/2013','dd/mm/yyyy')

SQL Queries in SQL Server and MySQL (Format - “MM/DD/YYYY”), Select * from EMPLOYEE where joining_date >'01/31/2013'

SQL Queries in MySQL (Format - “YYYY-DD-MM”), Select * from EMPLOYEE where joining_date > '2013-01-31'

35. Get Joining Date and Time from employee table

SQL Queries in Oracle, select to_char(JOINING_DATE,'dd/mm/yyyy hh:mi:ss') from EMPLOYEE

SQL Queries in SQL Server, Select convert(varchar(19),joining_date,121) from EMPLOYEE

SQL Queries in MySQL, Select CONVERT(DATE_FORMAT(joining_date,'%Y-%m-%d-%H:%i:00'),DATETIME) from EMPLOYEE

36. Get Joining Date,Time including milliseconds from employee table

SQL Queries in Oracle, select to_char(JOINING_DATE,'dd/mm/yyyy HH:mi:ss.ff') from EMPLOYEE . Column Data Type should be “TimeStamp”

SQL Queries in SQL Server, select convert(varchar,joining_date,121) from EMPLOYEE

SQL Queries in MySQL, Select MICROSECOND(joining_date) from EMPLOYEE

37. Get difference between JOINING_DATE and INCENTIVE_DATE from employee and incentives table

Select FIRST_NAME,INCENTIVE_DATE - JOINING_DATE from employee a inner join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID
38. Get database date

SQL Queries in Oracle, select sysdate from dual

SQL Queries in SQL Server, select getdate()

SQL Query in MySQL, select now()



SQL Queries Interview Questions and Answers on "SQL Escape Characters" - Examples

39. Get names of employees from employee table who has '%' in Last_Name. Tip : Escape character for special characters in a query.

SQL Queries in Oracle, Select FIRST_NAME from employee where Last_Name like '%?%%'
SQL Queries in SQL Server, Select FIRST_NAME from employee where Last_Name like '%[%]%'
SQL Queries in MySQL,Select FIRST_NAME from employee where Last_Name like '%\%%'

40. Get Last Name from employee table after replacing special character with white space
SQL Queries in Oracle, Select translate(LAST_NAME,'%',' ') from employee

SQL Queries in SQL Server and MySQL, Select REPLACE(LAST_NAME,'%',' ') from employee

SQL Queries Interview Questions and Answers on "SQL Group By Functions" - Examples

41. Get department,total salary with respect to a department from employee table.

Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by department

42. Get department,total salary with respect to a department from employee table order by total salary descending

Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by DEPARTMENT order by Total_Salary descending

SQL Queries Interview Questions and Answers on "SQL Mathematical Operations using Group By" - Examples

43. Get department,no of employees in a department,total salary with respect to a department from employee table order by total salary descending

Select DEPARTMENT,count(FIRST_NAME),sum(SALARY) Total_Salary from employee group by DEPARTMENT order by Total_Salary descending

44. Get department wise average salary from employee table order by salary ascending

select DEPARTMENT,avg(SALARY) AvgSalary from employee group by DEPARTMENT order by AvgSalary asc

45. Get department wise maximum salary from employee table order by salary ascending
select DEPARTMENT,max(SALARY) MaxSalary from employee group by DEPARTMENT order by MaxSalary asc

46. Get department wise minimum salary from employee table order by salary ascending

select DEPARTMENT,min(SALARY) MinSalary from employee group by DEPARTMENT order by MinSalary asc

47. Select no of employees joined with respect to year and month from employee table

SQL Queries in Oracle, select to_char (JOINING_DATE,'YYYY') Join_Year,to_char (JOINING_DATE,'MM') Join_Month,count(*) Total_Emp from employee group by to_char (JOINING_DATE,'YYYY'),to_char(JOINING_DATE,'MM')

SQL Queries in SQL Server, select datepart (YYYY,JOINING_DATE) Join_Year,datepart (MM,JOINING_DATE) Join_Month,count(*) Total_Emp from employee group by datepart(YYYY,JOINING_DATE), datepart(MM,JOINING_DATE)

SQL Queries in MySQL, select year (JOINING_DATE) Join_Year,month (JOINING_DATE) Join_Month,count(*) Total_Emp from employee group by year(JOINING_DATE), month(JOINING_DATE)

48. Select department,total salary with respect to a department from employee table where total salary greater than 800000 order by Total_Salary descending

Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by DEPARTMENT having sum(SALARY) > 800000 order by Total_Salary desc


Query for finding max salary from table employee as a department wise..
.
select max(salary), department from employee group by department


SQL Queries Interview Questions and Answers on "SQL Joins" - Examples

49. Select first_name, incentive amount from employee and incentives table for those employees who have incentives

Select FIRST_NAME,INCENTIVE_AMOUNT from employee a inner join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID

50. Select first_name, incentive amount from employee and incentives table for those employees who have incentives and incentive amount greater than 3000

Select FIRST_NAME,INCENTIVE_AMOUNT from employee a inner join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID and INCENTIVE_AMOUNT > 3000

51. Select first_name, incentive amount from employee and incentives table for all employes even if they didn't get incentives

Select FIRST_NAME,INCENTIVE_AMOUNT from employee a left join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID

52. Select first_name, incentive amount from employee and incentives table for all employees even if they didn't get incentives and set incentive amount as 0 for those employees who didn't get incentives.

SQL Queries in Oracle, Select FIRST_NAME,nvl(INCENTIVE_AMOUNT,0) from employee a left join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID

SQL Queries in SQL Server, Select FIRST_NAME, ISNULL(INCENTIVE_AMOUNT,0) from employee a left join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID

SQL Queries in MySQL, Select FIRST_NAME, IFNULL(INCENTIVE_AMOUNT,0) from employee a left join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID

53. Select first_name, incentive amount from employee and incentives table for all employees who got incentives using left join

SQL Queries in Oracle, Select FIRST_NAME,nvl(INCENTIVE_AMOUNT,0) from employee a right join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID

SQL Queries in SQL Server, Select FIRST_NAME, isnull(INCENTIVE_AMOUNT,0) from employee a right join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID

SQL Queries in MySQL, Select FIRST_NAME, IFNULL(INCENTIVE_AMOUNT,0) from employee a right join incentives B on A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID

54. Select max incentive with respect to employee from employee and incentives table using sub query

SQL Queries in Oracle, select DEPARTMENT,(select nvl(max(INCENTIVE_AMOUNT),0) from INCENTIVES where EMPLOYEE_REF_ID = EMPLOYEE_ID) Max_incentive from EMPLOYEE

SQL Queries in SQL Server, select DEPARTMENT,(select ISNULL(max(INCENTIVE_AMOUNT),0) from INCENTIVES where EMPLOYEE_REF_ID = EMPLOYEE_ID) Max_incentive from EMPLOYEE

SQL Queries in SQL Server, select DEPARTMENT,(select IFNULL (max(INCENTIVE_AMOUNT),0) from INCENTIVES where EMPLOYEE_REF_ID = EMPLOYEE_ID) Max_incentive from EMPLOYEE

Advanced SQL Queries Interview Questions and Answers on "Top N Salary" - Examples

55. Select TOP 2 salary from employee table

SQL Queries in Oracle, select * from (select * from employee order by SALARY desc) where rownum < 3

SQL Queries in SQL Server, select top 2 * from employee order by salary desc

SQL Queries in MySQL, select * from employee order by salary desc limit 2

56. Select TOP N salary from employee table

SQL Queries in Oracle, select * from (select * from employee order by SALARY desc) where rownum < N + 1

SQL Queries in SQL Server, select top N * from employee

SQL Queries in MySQL, select * from employee order by salary desc limit N

57. Select 2nd Highest salary from employee table

SQL Queries in Oracle, select min(salary) from (select * from (select * from employee order by SALARY desc) where rownum < 3)

SQL Queries in SQL Server, select min(SALARY) from (select top 2 * from employee) a

SQL Queries in MySQL, select min(SALARY) from (select * from employee order by salary desc limit 2) a

58. Select Nth Highest salary from employee table

SQL Queries in Oracle, select min(salary) from (select * from (select * from employee order by SALARY desc) where rownum < N + 1)

SQL Queries in SQL Server, select min(SALARY) from (select top N * from employee) a

SQL Queries in MySQL, select min(SALARY) from (select * from employee order by salary desc limit N) a

SQL Queries Interview Questions and Answers on "SQL Union" - Examples

59. Select First_Name,LAST_NAME from employee table as separate rows

select FIRST_NAME from EMPLOYEE union select LAST_NAME from EMPLOYEE

60. What is the difference between UNION and UNION ALL ?

Both UNION and UNION ALL is used to select information from structurally similar tables. That means corresponding columns specified in the union should have same data type. For example, in the above query, if FIRST_NAME is DOUBLE and LAST_NAME is STRING above query wont work. Since the data type of both the columns are VARCHAR, union is made possible. Difference between UNION and UNION ALL is that , UNION query return only distinct values.


"Advanced SQL Queries Interview Questions and Answers"

61. Select employee details from employee table if data exists in incentive table ?

select * from EMPLOYEE where exists (select * from INCENTIVES)

Explanation : Here exists statement helps us to do the job of If statement. Main query will get executed if the sub query returns at least one row. So we can consider the sub query as "If condition" and the main query as "code block" inside the If condition. We can use any SQL commands (Joins, Group By , having etc) in sub query. This command will be useful in queries which need to detect an event and do some activity.

62. How to fetch data that are common in two query results ?

select * from EMPLOYEE where EMPLOYEE_ID INTERSECT select * from EMPLOYEE where EMPLOYEE_ID < 4

Explanation : Here INTERSECT command is used to fetch data that are common in 2 queries. In this example, we had taken EMPLOYEE table in both the queries.We can apply INTERSECT command on different tables. The result of the above query will return employee details of "ROY" because, employee id of ROY is 3, and both query results have the information about ROY.

63. Get Employee ID's of those employees who didn't receive incentives without using sub query ?

select EMPLOYEE_ID from EMPLOYEE

MINUS

select EMPLOYEE_REF_ID from INCENTIVES


Explanation : To filter out certain information we use MINUS command. What MINUS Command odes is that, it returns all the results from the first query, that are not part of the second query. In our example, first three employees received the incentives. So query will return employee id's 4 to 8.

64. Select 20 % of salary from John , 10% of Salary for Roy and for other 15 % of salary from employee table

SELECT FIRST_NAME, CASE FIRST_NAME WHEN 'John' THEN SALARY * .2 WHEN 'Roy' THEN SALARY * .10 ELSE SALARY * .15 END "Deduced_Amount" FROM EMPLOYEE


Explanation : Here we are using SQL CASE statement to achieve the desired results. After case statement, we had to specify the column on which filtering is applied. In our case it is "FIRST_NAME". And in then condition, specify the name of filter like John, Roy etc. To handle conditions outside our filter, use else block where every one other than John and Roy enters.

65. Select Banking as 'Bank Dept', Insurance as 'Insurance Dept' and Services as 'Services Dept' from employee table

SQL Queries in Oracle, SELECT distinct DECODE (DEPARTMENT, 'Banking', 'Bank Dept', 'Insurance', 'Insurance Dept', 'Services', 'Services Dept') FROM EMPLOYEE

SQL Queries in SQL Server and MySQL, SELECT case DEPARTMENT when 'Banking' then 'Bank Dept' when 'Insurance' then 'Insurance Dept' when 'Services' then 'Services Dept' end FROM EMPLOYEE

 
Explanation : Here DECODE keyword is used to specify the alias name. In oracle we had specify, Column Name followed by Actual Name and Alias Name as arguments. In SQL Server and MySQL, we can use the earlier switch case statements for alias names.

66. Delete employee data from employee table who got incentives in incentive table

delete from EMPLOYEE where EMPLOYEE_ID in (select EMPLOYEE_REF_ID from INCENTIVES)

 
Explanation : Trick about this question is that we can't delete data from a table based on some condition in another table by joining them. Here to delete multiple entries from EMPLOYEE table, we need to use Subquery. Entries will get deleted based on the result of Subquery.

67. Insert into employee table Last Name with " ' " (Single Quote - Special Character)

Tip - Use another single quote before special character

Insert into employee (LAST_NAME) values ('Test''')

68. Select Last Name from employee table which contain only numbers

Select * from EMPLOYEE where lower(LAST_NAME) = upper(LAST_NAME)

 
Explanation : Here in order to achieve the desired result, we use ASCII property of the database. If we get results for a column using Lower and Upper commands, ASCII of both results will be same for numbers. If there is any alphabets in the column, results will differ.

69. Write a query to rank employees based on their incentives for a month
select FIRST_NAME,INCENTIVE_AMOUNT,DENSE_RANK() OVER (PARTITION BY INCENTIVE_DATE ORDER BY  INCENTIVE_AMOUNT DESC) AS Rank from EMPLOYEE a, INCENTIVES b where a.EMPLOYEE_ID = b.EMPLOYEE_REF_ID

 
Explanation : Here in order to rank employees based on their rank for a month, DENSE_RANK keyword is used. Here partition by keyword helps us to sort the column with which filtering is done. Rank is provided to the column specified in the order by statement. The above query ranks employees with respect to their incentives for a given month.


70. Update incentive table where employee name is 'John'

Explanation : Here we need to join Employee and Incentive Table for updating the incentive amount. But for update statement joining query wont work. We need to use sub query to update the data in the incentive table. SQL Query is as shown below.
update INCENTIVES set INCENTIVE_AMOUNT = '9000' where EMPLOYEE_REF_ID =(select EMPLOYEE_ID from EMPLOYEE where FIRST_NAME = 'John' )

SQL Queries Interview Questions and Answers on "SQL Table Scripts" - Examples

71. Write create table syntax for employee table
Oracle -

CREATE TABLE EMPLOYEE (

EMPLOYEE_ID NUMBER,

FIRST_NAME VARCHAR2(20 BYTE),

LAST_NAME VARCHAR2(20 BYTE),

SALARY FLOAT(126),

JOINING_DATE TIMESTAMP (6) DEFAULT sysdate,

DEPARTMENT VARCHAR2(30 BYTE) )


SQL Server -

CREATE TABLE EMPLOYEE(

EMPLOYEE_ID int NOT NULL,

FIRST_NAME varchar(50) NULL,

LAST_NAME varchar(50) NULL,

SALARY decimal(18, 0) NULL,

JOINING_DATE datetime2(7) default getdate(),

DEPARTMENT varchar(50) NULL)

72. Write syntax to delete table employee

DROP table employee;

73. Write syntax to set EMPLOYEE_ID as primary key in employee table

ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY KEY(EMPLOYEE_ID)

74. Write syntax to set 2 fields(EMPLOYEE_ID,FIRST_NAME) as primary key in employee table

ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY KEY(EMPLOYEE_ID,FIRST_NAME)

75. Write syntax to drop primary key on employee table

Alter TABLE EMPLOYEE drop CONSTRAINT EMPLOYEE_PK;

76. Write Sql Syntax to create EMPLOYEE_REF_ID in INCENTIVES table as foreign key with respect to EMPLOYEE_ID in employee table

ALTER TABLE INCENTIVES ADD CONSTRAINT INCENTIVES_FK FOREIGN KEY (EMPLOYEE_REF_ID) REFERENCES EMPLOYEE(EMPLOYEE_ID)

77. Write SQL to drop foreign key on employee table

ALTER TABLE INCENTIVES drop CONSTRAINT INCENTIVES_FK;

78. Write SQL to create Orcale Sequence

CREATE SEQUENCE EMPLOYEE_ID_SEQ START WITH 0 NOMAXVALUE MINVALUE 0 NOCYCLE NOCACHE NOORDER;

79. Write Sql syntax to create Oracle Trigger before insert of each row in employee table

CREATE OR REPLACE TRIGGER EMPLOYEE_ROW_ID_TRIGGER

BEFORE INSERT ON EMPLOYEE FOR EACH ROW

DECLARE

seq_no number(12);

BEGIN

select EMPLOYEE_ID_SEQ.nextval into seq_no from dual ;

:new EMPLOYEE_ID := seq_no;

END;

SHOW ERRORS;

84. What is SQL Injection ?
SQL Injection is one of the the techniques uses by hackers to hack a website by injecting SQL commands in data fields.

85. Transaction and rollback  ?
A transaction is the propagation of one or more changes to the database.
When one or more related SQL Commands are executed and if any one statement failed to execute, we need to rollback the entire related operations that has been executed. In such a scenario, Transactions are used. 
begin transaction

Delete from employee where ID = 1

 rollback transaction
                                                                                                                                                                                                    Next.......


C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...