Saturday

Top 10 Frequently asked SQL Query Interview Questions

Introduction

In this article, I am giving a few cases of SQL inquiries which is frequently approached when you go for a programming interviews, having maybe a couple year experience on this field. Regardless of whether you go for Java engineer position, QA, BA, supports professional,project manager or some other specialised position, may questioner anticipate that you will answer essential inquiries from Database and SQL. It's likewise clear that in the event that you are working from maybe a couple a long time on any venture there is great possibility that you run over to deal with database, composing SQL queries to insert, refresh, erase and select records. One straightforward yet viable approach to check competitor's SQL aptitude is by soliciting these sorts from basic inquiry. They are neither  complex nor big, yet they cover all key idea a software engineer should think about SQL.
Top 10 Frequently asked SQL Query Interview Questions

Earlier articles on Interview Questions and Answers frequently asked on MVC and OOPS as below:

SQL Query Interview Questions and Answers

• How to find second highest salary of Employee by SQL?
Second highest salary of an employee can be found in many ways, one can use either SQL Join or Sub-query in order to solve this problem.
select MAX(Salary) FROM tblEmployee WHERE Salary NOT IN (select MAX(Salary) from tblEmployee);

• How to find maximum salary from each office by SQL query?

One can find the maximum salary for every office by gathering all records by DepartmentID and afterward utilizing MAX() function to compute greatest salary in each group or each office.
SELECT DeptID, MAX(Salary) FROM tblEmployee GROUP BY DeparmentID.

• Compose SQL Query to show the present date.

SQL has inbuilt function called GetDate() which returns the current timestamp. This will work in Microsoft SQL Server, different sellers like Oracle and MySQL also has comparable capacities.
SELECT GetDate(); 

• Compose a SQL Query to check whether date is of given format or not.

SQL has IsDate() function which is utilised to check passed value is a date or not of determined arrangement, it returns 1(true) or 0(false) in like manner.
SELECT  ISDATE('09/09/2017') AS "MM/DD/YYYY";

• Compose a SQL Query to print the name of the employee whose DOB is between 09/09/2016 to 09/09/2017.

This SQL question is precarious, however you can use BETWEEN condition to get all records whose date fall between two dates.
SELECT DISTINCT EmployeeName FROM tblEmployees WHERE DOB  BETWEEN ‘09/09/2016’ AND ‘09/09/2017’;

• Compose a SQL query to seek out names of employee begin with ‘T’ .

-- this will search only employee name starts from character 'T'
SELECT * FROM EmployeeName WHERE EmployeeName like 'T%';
-- OR you can also write a query to find all EmployeeName those who have character 'T' 
SELECT * FROM EmployeeName WHERE EmployeeName like '%T%';

• What is SQL Server Agent?

SQL Server agent plays a vital role within the every day tasks of a info administrator (DBA). Its purpose is to ease the implementation of tasks for the DBA, with its full-perform planning engine, that permits you to schedule your own jobs and scripts.

What is Trigger?

Trigger permits us to execute a batch of SQL code once AN insert, update or delete command is dead against a selected table. Triggers square measure special varieties of keep procedures that square measure outlined to execute mechanically in situation of or once knowledge modifications. They will be dead mechanically on the insert, delete and update operation.

• What is a Temporary table in SQL Server?

More or less, a temp table is a transitory storage structure. It implies you can utilise a temp table to store information incidentally so you can control and change it before it achieves its destination format.

• Types of Temporary Tables?

  • Local Temp Table
  • Global Temp Table
Local temporary tables can be available to current user connection and they are automatically deleted once the user connection discontinue from database. Local temp tables are used with (#) sign.
Global Temporary tables are like permanent tables in database and it is available to any user by any connection and it can be deleted only when all connections are close.

Conclusion

Despite the fact that requesting that hopefuls compose SQL query is a superior approach to check one's SQL abilities, some of the time it likewise pays to make theoretical inquiries just to check whether knows about fundamental ideas or not, especially amid telephone interviews.

Relevant Reading

Sunday

SQL PERFORMANCE: HOW TO IMPROVE SQL QUERY PERFORMANCE

INTRODUCTION

SQL query performance improvement is an extremely intriguing topic amongst developers and the client group. Clients dependably needs a quick reaction on their data recovery actions and developers set forth their earnest attempts to give the information in the most brief time, be that as it may, there is no clear approach to characterise what is the best performance. At some point it's easily proven wrong what is good and what is bad execution of a question however generally on the off chance that you take after prescribed procedures amid development, you can give the best inquiry reaction to clients and avoid such discussions about optimal performance.

HOW TO IMPROVE SQL QUERY PERFORMANCE

There are multiple approaches to improve SQL query performance, which falls under different classes like re-composing the SQL query, creation and use of Indexes, management of statistics, etc.
Here are some SQL best practices to ensure query optimisation:
Avoid multiple joins: Avoid writing a SQL query using multiple joins with outer joins, cross apply, outer apply and other complex sub queries.
Eliminate cursors: Remove cursors from query and opt for set-based query as it is more efficient than cursor-based.
Avoid using non-correlated Scalar Sub query: Re-write query to eliminate non-correlated scalar sub query as a separate query and store output in a variable.
Avoid Multi-statement Table Valued Functions: Avoid Multi-statement TVFs as they are costlier than inline TFVs.
Clustered and Non-Clustered index: Create Clustered and Non-clustered index in SQL. These allows SQL server to rapidly and proficiently discover rows associated with key values.
Restrict size of working data set: Analyse the tables utilised as a part of the SELECT statement to check whether you can apply filters in the WHERE clause of your statement. An example case will be when a query initially functioned well when there were just a few  thousand lines in the table. As the application grew the query slowed. The answer might be as basic as limiting the query to look  at the present month's data. When you have queries that have sub-selects, apply filters to the internal statement of the sub-selects rather than the external statements.
Eliminate unnecessary tables: Writing SQL statements is a procedure that generally takes various iterations as you write and test your SQL statements. Amid development it is conceivable that you add tables to the query that might not have any effect on the data returned by the SQL code. By deleting these unnecessary tables you decrease the degree of processing the database has to do.
Exclude prefix “sp_”: Avoid prefix “sp_” with user defined stored process name since SQL server search the user defined process in the master database before in the current session database.
UNION ALL in place of UNION: UNION ALL does not need to make the additional stride of checking the result sets and separating just the unique values, so use UNION ALL over UNION, since it doesn't need to sort the result set.

SQL Performance

Specify All Primary Keys and Foreign Key Relationships: Primary keys and foreign key relationships that are effectively characterised help ensure that you can compose optimal queries. One common consequence of incorrect relationships is adding DISTINCT clauses to dispose of excess data from result sets.
Examine Your Server Specifications and Performance: You should have a database maintenance plan with focus on index management and database reduction. Your database server should have required RAM to support SQL Server. SSIS ETL processes should run on an ETL or staging server if they are memory/CPU intensive for long periods of time.
Use Stored Procedures or Parameterized Queries: The SQL server saves execution plans for stored procedures and parameterized queries under most circumstances. This allows them to be reused on later calls.

Add Schema Name before your SQL object name
To improve your SQL query performance, you are required to apply schema name followed by  “.”
 -- dbo is here used as schema name
SELECT col_1, col_2, col_3 from dbo.tblMyTable;
-- Should Avoid T-SQL statement like this
SELECT col_1, col_2, col_3 from tblMyTable;
Best Practice by Applying SET NOCOUNT ON
After applying SET NOCOUNT ON, it is quite sure to improve your SQL statement performance. SQL Server returns no of rows affected after statements SELECT, INSERT, UPDATE and DELETE statement, after applying SET NOCOUNT ON we can stop it.
CREATE PROCEDURE USP_MyFirstProcedure
AS
SET NOCOUNT ON
BEGIN
.
.
.
END
Always Apply TRY-Catch
By practising TRY-Catch, we can cut deadlocks caused by complex queries.
BEGIN TRY  
     { sql_statement | statement_block }  
END TRY  
BEGIN CATCH  
     [ { sql_statement | statement_block } ]  
END CATCH  

CONCLUSION

These are some quick and simple techniques for enhancing query performance for some long-running process. While these systems won't have any significant bearing to each issue you may experience but, they will help in a few cases.

Relevant Reading

.Net Core: What Is New In ASP.NET Core 2.0

Introduction

ASP.NET is the next evolution of Microsoft for the web pages that are supposed to be server driven. Rather than modifying and amending the ASP and adding new features and functionalities into it, new software called the ASP.NET has come up. It is completely and overhauls as it provides an interface for programming that lets the developers keep coding in an advanced way for the internet. These are the developers who are familiar with the concepts of Visual Basic as well as the other tools that are based on the development of relations between client and server. The most well-known providers of hosting services support the technologies that have a .NET extension; they support both ASP.NET core 2.0 and ASP.NET core 3.5.  The new .net core 2.0 features are also supported by these providers.

Things to know about the latest ASP.NET Core 2.0:

In the latest ASP.NET core 2.0 hosting those developers who have a past record of developing different stuff in the world of client and server are allowed for transferring their skills seamlessly to the web. Those developers and programmers who also have been writing programs in different languages including Java, Visual Basic, C++, etc. for the purpose of development on the internet are allowed for using the already existing components. This lets them keep working with their web pages of ASP.NET core and the web forms as well. In the latest release of ASP.NET, these functionalities have been enhanced to a great level.
What Is New In ASP.NET Core 2.0

New features added in ASP.NET core:

Support for Razor Pages

The support for Razor pages is one of the features that have been recently added to the functionality of ASP.NET core. MVC has the same features as the Razor pages.

New framework capabilities

The APIs, as well as the ability for referencing the complete Framework Libraries, has been expanded in the .NET core 2.0.

New OS addons

There is an expanded support of Operating System.

New Optimisations

Now .NET core is supported by the Visual Beginners All-purpose Symbolic Instruction Code. It allows the users to make console applications and the class libraries.

Csproj is the new game

The project files of xproj are to be replaced by the csproj’s new version.

Legacy Support

The MS builds have started working again in the new version.

New updates for visual studio

There are certain tooling enhancements done by Visual Studio 2017 in the new version of .NET.

Conclusion

You should keep over viewing ASP.NET Core 2.0, and its latest versions so that you do not miss out any of its new functionalities. Recently, the tools for developers and the integration of the database for the latest version of ASP.NET have also been designed in such a way that it becomes very easy to use. By following the easy steps, you can go for .net core 2.0 download and further explore about the software.

Suggested Reading

OPTIMAL PERFORMANCE: UNION VS UNION ALL IN SQL SERVER

Introduction

From time to time and there is a need to join information from numerous tables or perspectives into one extensive data set. This might be for tables with comparable data inside a similar database or perhaps there is a need to consolidate comparative data crosswise over databases or even across servers. In this article we will analyse how to use UNION versus UNION ALL commands and how they contrast. In my previous article, I explained differences between a clustered and a non-clustered index.

Optimal Performance Comparison Union vs. Union All

The UNION command is utilised to choose the related data from two tables, which resembles a JOIN command. In any case, when utilising UNION order, all the chose columns should be of similar data type. With UNION, just distinct values are chosen.
UNION ALL command is equivalent to UNION command, aside from that UNION ALL chooses every values. Hence, it does not remove any duplicate values.
Since this does not evacuate duplicate values this procedure is speedier, but rather on the off chance that you don't need duplicate records you should utilise the UNION command.
The decision is easy if you know the answer to the Question "Would i like to take out duplicate rows when I join 2 result sets with this operation?”
On the off chance that yes, at that point use UNION . In any case, know that a UNION will make the additional stride of checking the outcome set and giving you ONLY unmistakable rows. So it will perform slower on the grounds that it needs to sort the result set.
On the off chance that its ensured that your two result sets which you need to join won't have any overlapping rows, or you couldn't care less if there are duplicate/over lapping rows, at that point you should use UNION ALL. Since UNION ALL does not need to make the additional stride of checking the result sets and separating just the unique values, so UNION ALL is generally preferable performing over UNION, since it doesn't need to sort the result set.

Video: UNION VS UNION ALL IN SQL SERVER

Creating Database Tables For Check Comparison


create table compareUnionvUnionaAll (col varchar(10))

insert into compareUnionvUnionaAll values ('technology')
insert into compareUnionvUnionaAll values ('crowds')
insert into compareUnionvUnionaAll values ('sql')
insert into compareUnionvUnionaAll values ('.net')

create table compareUnionvUnionaAll1 (col varchar(10))

insert into compareUnionvUnionaAll1 values ('android')
insert into compareUnionvUnionaAll1 values ('MEAN')
insert into compareUnionvUnionaAll1 values ('sql')
insert into compareUnionvUnionaAll1 values ('.net')
List Records From Both Tables
SELECT * FROM compareUnionvUnionaAll;
SELECT * FROM compareUnionvUnionaAll1;

Results Overview

Table Results Overview

Lets Execute Union All Command

select * from compareUnionvUnionaAll
Union ALL
select * from compareUnionvUnionaAll1

Result Overview of Union ALL Command

Result Overview of Union ALL Command

Lets Check Execution Plan For Union ALL Optimal Comparison

Check Execution Plan For Union ALL Optimal Comparison

UNION Command Results Overview

select * from compareUnionvUnionaAll
Union
select * from compareUnionvUnionaAll1
UNION Command Results Overview

Lets Check For Union Optimal Comparison

Check For Union Optimal Comparison

I think you may notice that UNION query cost is more than UNION ALL which is marked red (63%).

Conclusion

UNION and UNION ALL collated as they are completely apart from each other, they both have different purposes.

Relevant Reading

Angular 4: What is New in Angular 4

INTRODUCTION 

In the realm of web application development, Angular is viewed as a standout amongst other open-source JavaScript frameworks. Angular 2 was released on September 14, 2016 and roughly 6 month after the release of Angular 2 , Angular 4 was made available.The final version was released on March 23, 2017. Let's examine why this update was released and what it adds to web development.

What is New in Angular 4

What is new in ANGULAR 4 and how it differs from ANGULAR 2?

When contrasted with Angular 2, there are heaps of new things added. New components as well as a few changes that enhanced old abilities. So how about we proceed onward to see the list.

  • Compact and Faster: With Angular 4, projects will expend less space and run faster than past variants.
  • View Engine size reduced: Size of view engine is reduced by approximately 60 percent.
  • Animation package: Angular 4.0 have pulled the animations out of @angular/core and set them into their own package. This means that if we don’t use animations, the extra code will not end up in production bundles.
  • *ngIf and *ngFor: NgIf syntax is extended to support the else clause to show the template when the condition is false.
  • Angular Universal: With Angular Universal, it's conceivable to render Angular applications outside of the program, for example specifically on the web server.
  • Compatible with Type Script 2.1 and 2.2: Type security of Angular applications and the speed of ngc-Compiler have been elevated.
  • Templates: Source maps are for templates too.Template Compiler will create source maps  for templates.

ANGULAR 4 Tutorial

The Video tutorial on Angular 4 is available on the YouTube channel Technology Crowds link is here.

Conclusion

Developers who have knowledge of AngularJS and Angular 2 will find the new update easy and helpful to use. With this new update Angular has shown the world that they are always ready to listen to developers’ community.

Suggested Reading

Thursday

What are the differences between a clustered and a non-clustered index

Introduction

Hope you liked my previous article on Understanding The Relationships in SQL Server. In this article, I am going to discuss clustered and non-clustered indexes in SQL. An index is a disk structure related with a table or view that accelerates the extraction of rows from the table or view. It contains keys created from one or more columns in the table or view. These keys are stored in a B-tree structure that allows SQL Server to rapidly and proficiently discover the rows associated with the key values.
differences between a clustered and a non-clustered index

SQL supports two types of indexes:

  • Clustered index
  • Non-clustered index

Clustered index

Clustered indexes sorts and stores data in table or view based on their key values. There is only one clustered index per table and this table with clustered index is known as clustered table.

Non-Clustered index

Non-clustered indexes have a separate structure from data rows. A non-clustered index comprises of non-clustered index key values. Each one of these key value entry has a pointer to the data rows that includes the key value. It is important for columns that have repeated values.

Difference between Clustered and Non-clustered index in SQL

The difference between clustered and non-clustered indexes is one of the most asked questions during interviews.
Given below are some of the differences between clustered and non-clustered indexes:
  1. Clustered index sorts data rows whereas non-clustered doesn't.
  2. One table can have one clustered index, but there is no such condition on non-clustered index.
  3. In many databases, a clustered index is directly made on primary key.
  4. Clustered Index is more faster to non clustered index because non clustered  physically stored in index order. 
  5. Non clustered index is more faster for insert and update rather than clustered index.
  6. Clustered index is stored logical so it don't require extra storage.

Conclusion

That’s all on difference between clustered and non-clustered indexes in SQL. Both indexes are extremely critical in SQL.

Relevant Reading

Wednesday

How to avoid duplicate records in SQL view using Entity Framework

Introduction

Sometimes while using SQL we experience that SQL query returns same or duplicate results. Since we expect and need a single result from the query, it is a problem. Here we will discuss what causes duplicate records and how to avoid them in SQL view using Entity Framework.

You can also know about how to Fix SQL error: 26 - A network-related error occurred in SQL Server by reading my previous article.

Duplicate rows in Entity Framework SQL View 

In Entity Framework primary key is known as entity key. Entity Framework auto set fields as entity key for those not null column and return the row that match those entity key that causes the problem.
The problem is on the application side Entity framework mapping, as object mapping rules in Entity framework are different with database. The Entity framework does the mapping on application memory with accordance to its designed logic when the query results returns from database. Entity Model has a unique way of handling rows with equal primary key values. To fix issue duplicate records in SQL view using Entity Framework, you need to write below code:
 How to avoid duplicate records in SQL view using Entity Framework

You can set AsNoTracking option directly on your view to resolve this issue.

context.myviewname.AsNoTracking().Where(x => x.ColumnName != null);

Conclusion

To avoid this problem the primary key columns should be chosen correctly. If primary key couldn't be chosen correctly due to null-values, we add a column to our view that always have a unique value for each row and make it primary key in entity model and set AsNoTracking. This is how explained  How to avoid duplicate records in SQL view using Entity Framework.

Relevant Reading