Wednesday, August 20, 2014

Remoting.Net vs Web Services

Both .Net Web services and .Net Remoting are Microsoft solutions for distributed application. Before choosing one of them for application development, let’s identify the differences between these technologies.
Protocol
.Net web services can be accessed only over HTTP whereas .Net remoting can be accessed over any protocol including TCP, HTTP, or SMTP.
Performance
In terms of performance, .Net remoting is faster than its counterpart web service when it uses TCP channel with binary formatter. But if you use soap formatter in .net remoting, web services with soap formatter either with TCP or HTTP channel provides faster solution.
Security
.NET Remoting can be hosted either in IIS or in other container. If hosted in IIS, .NET Remoting can benefit all security advantages of IIS. But when hosted other than IIS, the application has to take care security aspect itself. 
On the other hand, .Net web services are hosted in IIS, by default. So, it leverages all features of security provided by IIS.
State Management
Web services are a stateless in nature like web application. You need to use state mechanism to retain state. You can use session or application object to maintain state. In .Net Remoting, Singleton objects can share state whereas if you don’t need to maintain state, you can use Singlecall objects.
Interoperability
Web services support heterogeneous environments which means client and remote object can be built in any platform.
.NET remoting requires the client be built using .NET, enforcing homogenous environment.
Reliability
Since .Net web services are hosted using IIS, they are reliable whereas .Net remoting application needs to maintain security on its own if not hosted using IIS. When hosted in IIS, .Net remoting is also as reliable as web services.
Ease of development
Create and consuming .Net web services are easier process. To create remoting object, you need create remote object, hosting application to host remoting object and configuration file to specify type of channel and formatter to be used by remoting object.
NET - difference between XML Web Services using ASMX and .NET Remoting using SOAP - June 24, 2009 at 10:30 AM by Amit Satpute
What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?
  • XML Web services are more restricted than objects exposed over .NET Remoting.
  • XML Web services support open standards that target cross-platform use.
  • XML Web services are generally easier to create and due to the restricted nature of XML Web services, the design issues are simplified.
  • XML Web services support only SOAP message formatting, which uses larger XML text messages.
  • Communication with .NET Remoting can be faster than XML Web service communication with a binary formatter.
  • XML Web services are designed for use between companies and organizations.
  • XML Web services don't require a dedicated hosting program because they are always hosted by ASP.NET.
  • Consumers can use XML Web services just as easily as they can download HTML pages from the Internet. Thus there's no need for an administrator to open additional ports on a firewall as they work through MS-IIS and ASP.NET


Testing and consuming a .Net web service.

Testing a Web Service
.NET has a test web page that ASP.NET uses automatically when you request the URL of an .asmx file in a browser. This page uses reflection to read and show information about the web services, such as the names of the methods it provides.
Consuming a Web Service
Web services are built on XML standard. So, a client needs to equip itself to understand XML-based message in order to exchange messages. The .Net framework provides proxy component that enable clients to interact with web services. The proxy has all necessary information that can be utilized by the client application to share data with web services. 
The proxy class wraps the calls to the web service's methods. It generates SOAP message format and manages the transmission of the messages over the network (using HTTP). When it receives the response message, it converts the results back to the corresponding .NET data types. 
You can create a proxy class in .NET in two ways: 

By using wsdl.exe command-line tool
By using Visual Studio web reference feature  

What are the data types supported by Web Services?

.Net web services are built on XML-based standards for exchanging data. This means .NET web services can support only those data types that can be recognized by the XML schema standard. There are many proprietary .Net objects such as FileSteam, Eventlog etc. are not supported in the web services. These data types are .Net specific types that are not universally recognized, i.e. .Net specific only.

You can even exchange custom objects using .Net web services. The only limitation is that only public data members are transmitted, and all public members and properties must use one of the other supported data types.
You can use DataSet and DataTable to return information from database but can't use other ADO.NET objects such as DataColumns and DataRows.
.Net offers a distributed technology called .Net remoting that can plays around wide range of .Net specific data type. But unfortunately, .Net remoting doesn't support client other than .Net.


Define the specifications that help in the discovery of a web service.

DISCO
DISCO, an abbreviation of discovery, is a file that groups together a list of related web services. A company that offers web services publishes a DISCO file on its server that has links of all the web services it provides. The client requests this file to see all the available web services. This standard is useful when client already know about a company that offers web services. You can also use DISCO standard while working in local network. It is not helpful to find all web services over the internet.

UDDI


UDDI (Universal Description, Discovery, and Integration) offers centralized directory for web services over the internet. It hosts web services from different companies and can be used by the clients to find web services of their specific need. To make web services shared publicly, they have to be published in UDDI.  

Explain in brief Web Service Standards

Following are the standards used by web services:
WSDL
WSDL is used to create interface definition for a web services. It describes all about methods to the client, i.e. methods available in a web service, their parameters and return values.
SOAP

SOAP, Simple Object Access Protocol is a communication protocol, a way to structure data, based on XML. The web services use SOAP message format to encode information before sending.
HTTP
The SOAP message format in web services uses HTTP as communication protocol, i.e. SOAP messages are sent over HTTP channels. 
DISCO
It is used to create discovery documents that provide links to multiple web service endpoints. The DISCO standard creates a single file that groups a list of related web services. A company can publish a DISCO file on its server that contains links to all the web services it provides. 
UDDI 
A standard for creating business registries that catalog companies, the web services they provide, and the corresponding URLs for their WSDL contracts.


Advantages of .Net Web Services

Web Services are supported on a wide range of platforms.
Web services may extend its interface and add new methods without affecting the clients as long as they still provide the old methods and parameters.
  • A client makes a request to a web service, the web service returns the result, and the connection is closed. There is no permanent connection. This makes it easy to scale up and support many clients at a time.
  • Firewalls can pose a challenge for distributed object technologies. The only thing that almost always gets through firewalls is HTTP traffic on ports 80 and 443. Because web services use HTTP, they can pass through firewalls without explicit configuration.


Web services vs. CORBA and DCOM

Web services
Web services use HTTP protocol for sending and receiving messages between the applications. 
The data encoding in web services is based on XML. 
Web services are defined using WSDL (Web Services Description Language).
  • Web services are discovered using UDDI (Universal Description, Discovery and Integration).
  • Web services are firewalls friendly.
  • Web services supports interoperability i.e. cross platform integration is possible.

CORBA and DCOM

  • These technologies use non-standard protocol, i.e. CORBA uses IIOP (Inter Internet Object Protocol), and DCOM uses RPC (Remote Procedure Calls)
  • CORBA components are defined using CORBA Interface Description Language; DCOM components are defined using Microsoft Interface definition languages
  • CORBA components are discovered using the CORBA registry, DCOM using the Registry.
  • DCOM is a proprietary protocol that does not support interoperability and has firewall problems as DCOM transfers data in binary format and it uses many ports to call remote functions.
  • CORBA uses the IIOP protocol, which is non-Internet friendly.
  • CORBA and DCOM are fine for building enterprise applications that runs on the same platform and not good enough for applications that span platforms and languages.


Explain in brief different distributed technologies.

The need of distributed technologies arises with the requirement of distributed computing applications. The distributed computing allows partitioning of application logic into units and spreading the unit over different computers of a network or across different networks. This helps in spreading out loads over many computers. The components once developed can be reuse by other applications. There are many technologies developed to allow the distribution and reuse of application logic.

Advantages of the distributed components:


  • The key benefit of having distributed components is that they spread out the load over different machines.
  • The components can be upgraded without disturbing the clients' code.
  • The distributed application improves security. For example, a company who has many agents wouldn’t like those agents to have direct access to its database. Instead, these agents can be granted access to the components running on the corporate server which can be controlled and restricted.  

Deploying a Web Service

Deploying the .Net Web Services is as simple as any ASP.NET application. Similar to ASP.NET applications, you need to copy or upload the .ASMX file and the .DISCO files to the appropriate directories, and that's it. 

Why do we need .Net Web Services?

We have a number of heterogeneous technologies available on internet. The demand for reusable components across platforms and programming languages are high. Most of the components have the limitation that they can't share or exchange data across different platforms, they are mostly language specific or platform specific. The technologies like COM, RMI, CORBA etc. contributed best to fulfill requirements to some extent, but components result from these said technologies are mostly either language specific or platform specific. 

To avoid above problem, we need to have web services. Through web services we have overcome the problem of interoperability between languages and platforms. Web services uses SOAP as transport protocol which uses a text based messaging model, i.e. XML to communicate between disparate systems. 


Explain when do we required ASP.NET web services.

ASP.NET web services are the great way to expose your middle tier components via internet. These components offer no issue communicating across firewalls as they use SOAP as transport protocols that transmit structured data using HTTP channel. Thus, message can be easily exchanged through port 80, i.e. through internet data port without being getting hampered by corporate firewalls or proxy server.
Web services can fit in the situation when we require integrating disparate systems written by separate vendors via internet. 

Web services are primarily being used for B2B integration like authorizing employees, supplier, electronically signing of invoice etc.

Explain how to document web services.

ASP.NET web services are considered as self documenting as they provides all information about what methods are available and what parameters they require using XML based standard called WSDL. We can also provide addition information about the web services using their WebService and WebMethod attributes.

You can add descriptions to each method through the Description property of the WebMethod attribute and to the entire web service as a whole using the Description property of the WebService attribute. You can also apply a descriptive name to the web service using the Name property of the WebService attribute. The attributes have name, description and namespace as properties which are shown in following example:
[WebService(Name = "Customer Service", Description = "Retrieve the Customer details",Namespace=http://www.apress.com/ProASP.NET/)]
public class Customer : System.Web.Services.WebService
{
     [WebMethod(Description = "Returns Customer Count")]
     public int GetCustomerCount()
     { ... }
     [WebMethod(Description = "Returns the list of Customer")]
     public DataSet GetCustomer()
     { ... }
}
Namespace allows your web service to be uniquely identified. By default, ASP.NET web services use the default XML namespace http://tempuri.org/, which is suitable only for testing. XML namespace simply identifies your web service. XML namespaces usually look like URLs. However, they don't need to correspond to a valid Internet location.

Explain the protocols a .Net Web Service uses.

In .Net, a web service is bind with three different protocols such as HTTP/POST, 

HTTP/GET, and SOAP. This allows client with three options to choose for 

communication. The protocols are included in the WSDL file that is automatically 

generated in .NET.

Http-Get and Http-Post can only be used when name/value pairs of data is dealt 

with. But when data is complex in nature such as ASP.NET dataset, XML notes 

etc, then we can use SOAP that serializes data in simpler form before sending.  

What is UDDI?

UDDI stands for Universal Description, Discovery and Integration. It is an open, 

Internet-based specification that offers directory service for storing information 

about web services.

What is SOAP?

SOAP, Simple Object Access Protocol is a communication protocol, a way to structure data before transmitting it, is based on XML standard. It is developed to allow communication between applications of different platforms and programming languages via internet.
It can use range of protocols such as HTTP, FTP, SMTP, Post office protocal 3(POP3) to carry documents.
Http-Get, Http-Post works with name/value pair which means transferring complex object is not possible with these protocols, whereas SOAP serializes complex structure, such as ASP.NET DataSets, complex arrays, custom types and XML nodes before transmitting and thus allows exchange of complex objects between applications.
Two components can easily communicate using Remote Procedure Calls protocol. But because of their compatibility and security issues, most of firewalls and proxy server block this type of messages. SOAP uses HTTP channel to transport which makes it widely accepted protocal over the internet.

What is .Net Web Service?

    • Web service is the way to publish application's function on web that can be accessible to the rest of the world.
    • Web services are the components that can be used by other applications
    • ASP.NET offers easy way to develop web services, just precede the functions with a special WebMethod ()> attribute in order them to work as Web Service.
    • Web services are discovered using UDDI directory services.
    • Web services are built on XML standard and use SOAP protocol that allows them to communicate across different platforms and programming languages.
    • Web services easily manage to work across corporate firewalls as they use HTTP protocol which is firewall friendly.
    • Web services platform elements are
      SOAP (Simple Object Access Protocol)
      UDDI (Universal Description, Discovery and Integration)
      WSDL (Web Services Description Language)
    • The web services are built on internet standards that are not platform or language specific.
    • The .Net framework provides in-built classes to build and consume web services.
    • The components offered by web services are reusable.
    • The examples of web service components can be shipment tracking, translation utility, weather forecasting, sports scores etc. 

Monday, August 11, 2014

How to Share PC internet to my mobile

1. Go to start button of win 7 or vista and type 'cmd', then right click on the 'cmd.exe' application and click on 'Run as Administrator' option.
Sorry for the small pics. Please click on them to see the enlarged view.


2. Now set up a wifi access point with name 'funkywifi' with a password 'password123'.
For that you have to type the following command :
netsh wlan set hostednetwork mode=allow ssid=funkywifi key=password123 keyusage=persistent 

Note: You can set any name to this access point by replacing 'funkywifi' with your required name.Similarly you can give any password/security key instead of 'password123' that must be a string with 8 to 63 ASCII characters.
If keyUsage is specified as 'persistent', the security key will be saved and used when the hosted network is started again in future. Otherwise it will be used only when the current or next time the hosted network is started. Once the hosted network is stopped, the temporary security key will be deleted from the system. If keyUsage is not specified, it is persistent by default.If you want to keep the password temporary replace 'persistent' with temporary'.

3. Once the command executes successfully. You can check your newly created hosted network configuration by typing the following on the same command prompt window:
netsh wlan show hostednetwork

Now that you have configured the access point network, follow step no. 6 to share your broadband or lan connection.
4. Now that you have configured a hosted network named 'funkywifi', you need to start it by the following command on the same command window:
netsh wlan start hostednetwork

Now you can check the same by opening either 'Network and sharing center' or by clicking connection button in right corner of taskbar.

5. To stop the connection type the following :
netsh wlan stop hostednetwork
[Remember everytime you do this , all these commands except the commands in step 3 and 5 needs administrative privilages.Hence you should follow the first step for doing the same.]

If you don't like to type all these lines every time you start your network, then skip steps 2,3,4 & 5. You can save the three commands as discussed in steps 2,4 and 5 in three different batch files , which can do the same task if you run them as administrator.
If you are not familiar with batch files then simply create desktop shortcuts of these commands by following these steps.
To do this using batch files, type the command of my 2nd Step i.e, "netsh wlan set hostednetwork mode=allow ssid=funkywifi key=password123 keyusage=persistent" in Notepad.exe and save it as "sethostednetwork.BAT".
Similarly save "netsh wlan start hostednetwork" as start.BAT and "netsh wlan stop hostednetwork" as 'stop.BAT".
Now to creat or configure a new connection you can right click on "sethostednetwork.BAT" file icon and click on 'run as administrator'.

To start the connection right click on "start.BAT" file icon and click on 'run as administrator'.
To stop the connection right click on "stop.BAT" file icon and click on 'run as administrator'.
If you want to change username and password just right click on the "sethostednetwork.BAT" file icon and click on edit option. After replacing the existing username or password save it.

6. Now this is an important step without this you can't share your laptop internet. For doing this go to 'Network and sharing center' and click on 'Change adapter settings'. If you find it difficult to find it, just type 'Network and sharing center' as search phrase.
Identify your broadband connection or your PC internet connection (for me it is 'Local Area Connection') , right click and goto properties and then click onto sharing tab.Check the "Internet Connection Sharing" button and select your home network connection from the given options in the same tab for me it is "Wireless Network Connection 2".Now click ok and you are done.
:P Not yet !! 

7. Once you can see your hosted network in 'Network and sharing center', go to Settings>Wireless and network>Wi-Fi Settings in your android device , and tap on "Turn on Wi-Fi" button. It will automatically detect your PC/Laptop wifi network. On clicking the same connection in your mobile you only have to give the password and tap on 'connect' button.
Once connected you can use your PC/Laptop internet.
     
Leave a comment if this helped you. I will be happy to see them. :)
Thanks.. :)
-Soham

Wednesday, August 6, 2014

Sunday, August 3, 2014

What is the Difference between Abstraction and Encspsulation

Abstraction is showing only necessary things, but Encapsulation is hiding complexity.
for example, if we have a user log in form then we need only user id and password and a function to put on login button this shows abstraction (only necessary things) but logic should be written in some other class file and this is Encapsulation(Hiding Complexity).

Saturday, July 26, 2014

Interview Questions on SQL are based on following two tables, Employee Table and Employee Incentive Table.
Table Name : Employee
EMPLOYEE_IDFIRST_NAMELAST_NAMESALARYJOINING_DATEDEPARTMENT
1JohnAbraham100000001-JAN-13 12.00.00 AMBanking
2MichaelClarke80000001-JAN-13 12.00.00 AMInsurance
3RoyThomas70000001-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
7TestName112365000001-JAN-13 12.00.00 AMServices
8TestName2Lname%60000001-FEB-13 12.00.00 AMInsurance

Table Name : Incentives

EMPLOYEE_REF_IDINCENTIVE_DATEINCENTIVE_AMOUNT
101-FEB-135000
201-FEB-133000
301-FEB-134000
101-JAN-134500
201-JAN-133500

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

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;
80. Oracle Procedure 81. Oracle View
An example oracle view script is given below

create view Employee_Incentive as select FIRST_NAME,max(INCENTIVE_AMOUNT) INCENTIVE_AMOUNT from EMPLOYEE a, INCENTIVES b where a.EMPLOYEE_ID = b.EMPLOYEE_REF_ID group by FIRST_NAME
82. Oracle materialized view - Daily Auto Refresh 
CREATE MATERIALIZED VIEW Employee_Incentive

REFRESH COMPLETE

START WITH SYSDATE

NEXT SYSDATE + 1 AS

select FIRST_NAME,INCENTIVE_DATE,INCENTIVE_AMOUNT from EMPLOYEE a, INCENTIVES b 

where a.EMPLOYEE_ID = b.EMPLOYEE_REF_ID
83. Oracle materialized view - Fast Refresh on Commit
Create materialized view log for fast refresh. Following materialized view script wont get executed if materialized view log doesn't exists


CREATE MATERIALIZED VIEW MAT_Employee_Incentive_Refresh

BUILD IMMEDIATE

REFRESH FAST ON COMMIT AS

select FIRST_NAME,max(INCENTIVE_AMOUNT) from EMPLOYEE a, INCENTIVES b

where a.EMPLOYEE_ID = b.EMPLOYEE_REF_ID group by FIRST_NAME
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.