Search

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday, July 4, 2023

IBM C# Interview Questions and Answers for 5 Years of Experience

Are you an experienced C# developer looking to join IBM? This article is designed to help you prepare for your IBM C# interview by providing a wide range of interview questions and expertly explained answers. Tailored specifically for professionals with 5 years of experience, this comprehensive collection covers essential topics such as C# language features, the .NET framework, object-oriented programming, database connectivity, and more. Dive into this valuable resource to boost your knowledge, build confidence, and excel in your IBM C# interview.

IBM C# Interview Questions and Answers for 5 Years of Experience


What is an interface in C#?

An interface in C# is a reference type that defines a contract for classes to follow. It specifies a set of methods, properties, and events that the implementing class must provide. Interfaces provide a way to achieve multiple inheritances in C#.

Example:

public interface IShape

{

    void Draw();

    double CalculateArea();

}

public class Circle : IShape

{

    public void Draw()

    {

        Console.WriteLine("Drawing a circle");

    }

    public double CalculateArea()

    {

        // Calculate and return the area of the circle

        return Math.PI * radius * radius;

    }

}


When do we use interfaces?

Interfaces are used when we want to define a contract that multiple classes can adhere to. It is commonly used for achieving abstraction, providing a common set of methods across different classes, and facilitating loose coupling between components.


What is inheritance? Why do we use inheritance?

Inheritance is a mechanism in object-oriented programming where one class inherits properties and behaviors from another class. It allows the creation of hierarchical relationships between classes. We use inheritance to promote code reuse, enhance modularity, and establish an "is-a" relationship between classes.


How many types of access modifiers are there in C#?

C# provides five access modifiers: public, private, protected, internal, and protected internal.


When do we use the private modifier?

The private access modifier is used to restrict access to members within the same class. It ensures that the member is only accessible from within the class itself and not from any derived classes or external code.

Example:

public class MyClass

{

    private int myPrivateField;

    private void MyPrivateMethod()

    {

        // Code here

    }

}


What is method overloading in C#?

Method overloading allows us to define multiple methods with the same name but different parameters in the same class. The compiler determines which method to invoke based on the arguments provided during the method call.

Example:

public class Calculator

{

    public int Add(int a, int b)

    {

        return a + b;

    }

    public double Add(double a, double b)

    {

        return a + b;

    }

}


What is method overriding?

Method overriding is a feature in C# that allows a derived class to provide its own implementation of a method that is already defined in the base class. It is used to achieve polymorphism and to specialize behavior in derived classes.

Example:

public class Shape

{

    public virtual void Draw()

    {

        Console.WriteLine("Drawing a shape");

    }

}

public class Circle : Shape

{

    public override void Draw()

    {

        Console.WriteLine("Drawing a circle");

    }

}


How do we use exception handling in C#?

Exception handling in C# is done using try-catch-finally blocks. The code that may raise an exception is placed inside the try block, and any potential exceptions are caught and handled in the catch block. The finally block is used to execute code that should always run, regardless of whether an exception occurs or not.

Example:

try

{

    // Code that may raise an exception

}

catch (Exception ex)

{

    // Handle the exception

}

finally

{

    // Code that always executes

}


What are the blocks available in a try-catch in C#?

The blocks available in a try-catch statement in C# are:

  • try: Contains the code that may raise an exception.
  • catch: Catches and handles the exception.
  • finally: Contains code that always executes, whether an exception occurs or not.


When does the catch block execute?

The catch block executes when an exception is thrown inside the try block that matches the type of the caught exception. It is responsible for catching and handling the exception.


Explain the difference between constant and static?

  • Constants: A constant is a value that cannot be changed once it is assigned. It is declared using the `const` keyword and must be initialized at the time of declaration. Constants are resolved at compile-time.
  • Static Variables: A static variable is associated with a class rather than an instance of the class. It is declared using the `static` keyword and retains its value throughout the program's execution. Static variables are shared among all instances of the class.

   Example:

   public class MyClass

   {

       public const int MyConstant = 10; // Constant

       public static int MyStaticVariable = 5; // Static Variable

   }


Tell me the difference between constant and readonly variables?

  • Constants: Constants are compile-time constants and their values are known and fixed at compile-time. They are implicitly static and can only be of a value type or string.
  • Readonly Variables: Readonly variables are runtime constants, and their values can be assigned at runtime. They are initialized either at the time of declaration or within the constructor. Readonly variables can be of any type, including reference types.

   Example:

   public class MyClass

   {

       public const int MyConstant = 10; // Constant

       public readonly int MyReadonlyVariable; // Readonly Variable

       public MyClass()

       {

           MyReadonlyVariable = 5;

       }

   }

  


What is an abstract class?

 An abstract class is a class that cannot be instantiated and serves as a base for deriving other classes. It may contain abstract methods (without implementation) that must be overridden in derived classes. Abstract classes provide a way to define common behavior and enforce certain rules for subclasses.


When do we use the `async` and `await` keywords?

The `async` and `await` keywords are used in asynchronous programming in C#. `async` is used to declare a method as asynchronous, and `await` is used to asynchronously wait for the completion of a task. They are commonly used when performing time-consuming operations, such as network requests or file operations, without blocking the main execution thread.

   Example:

   public async Task GetDataAsync()

   {

       // Perform asynchronous operations

       await DoSomethingAsync();

       await DoAnotherTaskAsync();

   }


Can you explain about garbage collection?

Garbage collection is an automatic memory management feature in .NET. It is responsible for reclaiming memory that is no longer in use by the application. The garbage collector identifies and collects objects that are no longer reachable, freeing up memory resources and improving performance. Developers do not need to manually deallocate memory for objects managed by the garbage collector.


Why are we using XAML?

XAML (eXtensible Application Markup Language) is used in WPF (Windows Presentation Foundation) for designing user interfaces and separating UI code from business logic. It provides a declarative way to define UI elements and their properties.


How many controls are there in WPF?

WPF offers a wide range of controls that can be used to build user interfaces. There are numerous controls available, including TextBox, Button, ComboBox, ListBox, Grid, etc.


Is it possible to create controls in code-behind in C#?

Yes, it is possible to create controls dynamically in the code-behind file using C#. For example, you can create a Button control and add it to a container like a Grid programmatically.

   Button button = new Button();

   button.Content = "Click me";

   grid.Children.Add(button);


What are the major properties (cases) we are using in ListView?

Some of the major properties commonly used in a ListView control include ItemsSource (to bind a collection of data), ItemTemplate (to define the appearance of each item), SelectedItem (to get or set the currently selected item), and IsItemClickEnabled (to enable item click events).


What are the types of resources available?

In XAML, there are several types of resources available, including StaticResource (used for one-time resource lookup), DynamicResource (used for dynamic resource lookup), and ThemeResource (used for theme-based resource lookup).


How many types of styles are available in XAML?

In XAML, there are three types of styles available: 

  • Explicit Styles: These are defined with a specific x:Key and applied to elements explicitly using the StaticResource markup extension.
  • Implicit Styles: These are defined without a key and are automatically applied to all elements of a certain type within a scope.
  • Default Styles: These are predefined styles that are applied to all elements of a specific type by default.


We have a Label, what is the purpose of horizontal alignment and vertical alignment?

  • The HorizontalAlignment property of a Label control determines how the content is horizontally aligned within the control. The options include Left, Center, Right, and Stretch.
  • The VerticalAlignment property determines how the content is vertically aligned within the control. The options include Top, Center, Bottom, and Stretch.


What is the purpose of MVVM?

MVVM (Model-View-ViewModel) is a software architectural pattern used in WPF applications. It separates the concerns of the user interface (View), application data and behavior (ViewModel), and the underlying data model (Model). It promotes separation of concerns and facilitates testability and maintainability of the codebase.


What are the types of databases available in MVVM?

In MVVM, the type of database used depends on the specific requirements of the application. MVVM is an architectural pattern and is not limited to a specific database technology. Common databases used with MVVM include SQL databases (e.g., SQL Server, MySQL) and NoSQL databases (e.g., MongoDB, Firebase).


What are the things we hold in MVVM?

In MVVM, we have three main components:

  • Model: It represents the data and business logic of the application.
  • View: It defines the user interface and visual elements.
  • ViewModel: It acts as an intermediary between the View and Model, providing data binding and commanding capabilities. The ViewModel holds data and exposes it to the View, as well as handles user interactions and updates the Model accordingly.

What are the types of binding mode?

The types of binding modes in WPF (Windows Presentation Foundation) are:

  • OneWay: Updates the target property when the source property changes.
  • TwoWay: Updates the source property when the target property changes and vice versa.
  • OneTime: Updates the target property with the initial value from the source property but doesn't track subsequent changes.


When do we use OneTime binding mode?

OneTime binding mode is used when you want to initialize the target property with the value from the source property, but you don't need to track subsequent changes.


How to connect a view and view model in WPF?

In WPF, you can connect a view and view model by setting the `DataContext` property of the view to an instance of the corresponding view model. This can be done in XAML or code-behind. For example:

   XAML:

        <Window x:Class="MyApp.MainWindow"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:local="clr-namespace:MyApp"

             Title="MainWindow">

         <Window.DataContext>

             <local:MainViewModel />

         </Window.DataContext>

         <!-- Rest of the XAML code -->

     </Window>    


What is the binding context?

The binding context refers to the object or data source to which a control is bound. It provides the properties or data that the control displays or interacts with.


Why do we use converters in XAML?

Converters in XAML are used to convert data from one format to another during the binding process. They allow you to perform custom logic to transform the data before it is displayed or assigned to a property.


Example of a converter:

Here's an example of a converter in WPF that converts a boolean value to a visibility value:

     public class BooleanToVisibilityConverter : IValueConverter

     {

         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

         {

             bool isVisible = (bool)value;

             return isVisible ? Visibility.Visible : Visibility.Collapsed;

         }

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

         {

             throw new NotImplementedException();

         }

     }


What is a custom control in XAML?

 A custom control in XAML is a control that is created by deriving from an existing control or from the `Control` class. It allows you to define custom behaviors, properties, and styles for a specific control type.


How many types of layout panels are there in XAML?

There are several types of layout panels available in XAML, including:

  • Grid
  • StackPanel
  • WrapPanel
  • DockPanel
  • Canvas
  • UniformGrid


What is a trigger in WPF, and how many types of triggers are there?

In WPF, a trigger is a mechanism that allows you to change the appearance or behavior of a control based on certain conditions. There are mainly three types of triggers:

  • Property Trigger
  • Data Trigger
  • Event Trigger


What is INotifyPropertyChanged?

INotifyPropertyChanged is an interface in C# that is used to notify clients (usually UI controls) that a property value has changed. It is commonly used in data binding scenarios to keep the UI in sync with the underlying data.


What is the difference between DBMS and RDBMS?

DBMS (Database Management System) refers to a system that manages databases, while RDBMS (Relational Database Management System) is a specific type of DBMS that organizes data into tables with relationships between them.


What is a primary key in a table?

A primary key is a unique identifier for a record in a table. It ensures that each row in the table is uniquely identifiable. In SQL, you can define a primary key using the `PRIMARY KEY` constraint.


What is a foreign key?

A foreign key is a column in a table that establishes a link or relationship with the primary key of another table. It is used to maintain referential integrity and enforce relationships between tables.


How do you join two tables?

In SQL, you can use the `JOIN` clause to combine rows from two or more tables based on a related column. Common types of joins include `INNER JOIN`, `LEFT JOIN`, `RIGHT JOIN`, and `FULL JOIN`.

Example:

SELECT * FROM table1 JOIN table2 ON table1.column = table2.column


When do we use the SELECT statement in SQL?

The SELECT statement is used to retrieve data from one or more tables in a database. It is commonly used to query and fetch specific data based on specified criteria.

Example:

SELECT * FROM table_name WHERE condition;


What is the syntax of creating a table?

The syntax for creating a table in SQL is as follows:

Example:

CREATE TABLE table_name (

   column1 datatype,

   column2 datatype,

   ...

);


How to delete a row with student ID 5 from the Student table?

To delete a specific row from a table, you can use the `DELETE` statement with the `WHERE` clause.

Example:

DELETE FROM Student WHERE student_id = 5;


Which keyword is used to delete an entire table?

 To delete an entire table, you can use the `DROP` statement followed by the table name.

Example:

DROP TABLE table_name;


What is the difference between DELETE and TRUNCATE?

The `DELETE` statement is used to delete specific rows from a table, while the `TRUNCATE` statement is used to remove all rows from a table, essentially resetting it.


What keyword is used to delete a single row?

The `DELETE` statement is used to delete a single row or multiple rows based on the specified condition.

Example:

DELETE FROM table_name WHERE condition;


What is a stored procedure and its use?

A stored procedure is a prepared SQL code that can be saved and reused. It allows you to encapsulate logic and execute complex database operations with parameters.


What is the syntax of creating a procedure?

The syntax for creating a stored procedure in SQL is as follows:

Example:

CREATE PROCEDURE procedure_name

AS

BEGIN

    -- SQL statements here

END


What is a temporary table?

A temporary table is a table that exists temporarily in the database and is automatically dropped when the session or connection ends. It is useful for storing intermediate results during complex operations.


How do you execute a procedure in SQL?

You can execute a stored procedure in SQL using the `EXECUTE` or `EXEC` keyword followed by the procedure name.

Example:

EXEC procedure_name;


How to execute a procedure with parameters?

When executing a procedure with parameters, you need to pass the values for the parameters in the `EXECUTE` statement.

Example:

EXEC procedure_name @parameter1 = value1, @parameter2 = value2;


How to connect SQL Server with a WPF application?

To connect SQL Server with a WPF application, you can use the ADO.NET framework and provide the appropriate connection string to establish a connection to the database.


What properties are available in a connection string?

The connection string for SQL Server includes properties such as server name, database name, authentication mode, username, password, and additional connection options.


What are the possibilities of exceptions in SQL Server connectivity using ADO.NET?

Possible exceptions when connecting to SQL Server using ADO.NET include `SqlException` for errors related to SQL Server, `InvalidOperationException` for invalid operation errors, and `IOException` for input/output errors.


What things should you check before connecting SQL Server with a WPF application?

Before connecting SQL Server with a WPF application, you should ensure that the SQL Server is running, the necessary permissions are set for the database, and the connection string is correct.


If I am going to get data from SQL to a WPF application, do I need to check if the internet is connected or not? What is the basis?

No, checking the internet connection is not required when retrieving data from SQL Server to a WPF application. The communication happens over the local network within the SQL Server and the application.


How many types of queries are available?

In SQL, there are several types of queries including `SELECT` (retrieve data), `INSERT` (insert data), `UPDATE` (modify data), and `DELETE` (remove data).


What is the difference between the `<div>` and `<table>` tags in HTML?

 The `<div>` tag is a block-level element used for grouping and styling content, while the `<table>` tag is used to display tabular data in rows and columns.


If I need to add a link in HTML, what tag should I use?

To add a link in HTML, you should use the `<a>` tag (anchor tag) along with the `href` attribute to specify the URL or destination.

Example:

<a href="https://example.com">Link Text</a>


How many types of CSS are available in HTML?

There are three types of CSS in HTML: inline CSS (using the `style` attribute), internal CSS (within the `<style>` tag in the `<head>` section), and external CSS (using a separate CSS file).



All the very best 











Saturday, July 1, 2023

Tech Mahindra C# and SQL Interview Questions for 2023

n this article, we will cover a wide range of Tech Mahindra C# and SQL Interview Questions for 2023 and answers related to various programming concepts and SQL. Each question will be accompanied by a detailed explanation, relevant code examples, and query snippets. Let's dive in!


Tech Mahindra C# and SQL Interview Questions for 2023


The Use of the 'using' Keyword

The 'using' keyword in C# is primarily used for automatic disposal of unmanaged resources. It ensures that the Dispose method of an object is called when it goes out of scope. Here's an example of its usage:

using (var connection = new SqlConnection(connectionString))

{

    // Code block where the connection is used

    // The connection will be automatically disposed at the end of the block

}


Types of Constructors

In C#, constructors are special methods used for initializing objects. There are three types of constructors:

  • Default Constructor: It has no parameters and is automatically generated if no constructor is defined explicitly.
  • Parameterized Constructor: It accepts parameters and initializes the object with provided values.
  • Copy Constructor: It creates a new object by copying the values from an existing object.


Object with a Class with a Private Constructor

If a class has a private constructor, objects cannot be directly instantiated outside the class. However, the class itself can create instances using static methods or properties within its scope. Here's an example:

public class MyClass

{

    private MyClass()

    {

        // Private constructor

    }

    public static MyClass CreateInstance()

    {

        return new MyClass();

    }

}

// Creating an object using the static method

var myObject = MyClass.CreateInstance();


Difference between String and StringBuilder

In C#, 'String' is an immutable type, which means once created, it cannot be changed. 'StringBuilder', on the other hand, is a mutable type specifically designed for efficient string manipulation. 'StringBuilder' is preferred for concatenating multiple strings or when frequent modifications to a string are required.


Sealed Class

A sealed class in C# is a class that cannot be inherited. It is marked with the 'sealed' keyword to prevent other classes from deriving from it. Sealed classes are used when you want to restrict inheritance to maintain control over the behavior and implementation of a class.


Extension Method

An extension method in C# allows adding new methods to an existing type without modifying the original type. It is defined in a static class and must be a static method. Extension methods are called as if they were instance methods of the extended type. Here's an example:

public static class StringExtensions

{

    public static bool IsNullOrEmpty(this string value)

    {

        return string.IsNullOrEmpty(value);

    }

}

// Usage of the extension method

string myString = "Hello";

bool isEmpty = myString.IsNullOrEmpty();


Difference between Private Constructor and Static Constructor

A private constructor is used to restrict the creation of objects from outside the class, while a static constructor is used to initialize the class itself. A private constructor can be called within the class, whereas a static constructor is invoked automatically before any static members of the class are accessed.


Difference between 'ref' and 'out'

Both 'ref' and 'out' are used to pass arguments by reference in C#. However, there is a key difference:

  • 'ref' requires the variable to be initialized before passing it to the method, whereas 'out' does not.
  • In 'ref', the variable passed to the method must be initialized, but in 'out', it must be assigned a value within the method before returning.


Encapsulation

Encapsulation is an object-oriented programming concept that combines data and methods into a single unit called a class. It provides data abstraction, hiding the internal details of how data is stored or processed, and exposes only necessary information through public methods or properties.


Types of Access Modifiers

In C#, there are five access modifiers:

  •     Public: Accessible from anywhere.
  •     Private: Accessible only within the same class.
  •     Protected: Accessible within the same class and derived classes.
  •     Internal: Accessible within the same assembly.
  •     Protected Internal: Accessible within the same assembly and derived classes.


How to access the protected modifier?

The protected modifier in object-oriented programming languages allows access to a member within the same class and its subclasses. To access a protected member in C#, you can create an instance of the subclass and access the protected member using the dot operator. Here's an example:

public class MyBaseClass

{

    protected int myProtectedField;

}

public class MySubClass : MyBaseClass

{

    public void AccessProtectedField()

    {

        myProtectedField = 10; // Accessing protected field

    }

}


What is garbage collection?

Garbage collection is an automatic memory management technique used in languages like C# to reclaim memory occupied by objects that are no longer in use. The garbage collector identifies and frees up memory that is no longer referenced by any active objects in the program, preventing memory leaks and reducing manual memory management overhead.


Difference between abstract class and interface?

In C#, an abstract class and an interface both provide a way to define contracts for derived classes, but they have some key differences. 

Abstract class: An abstract class can have both defined and undefined (abstract) members. It can provide partial implementation of methods and can have fields and constructors. It cannot be instantiated directly but serves as a base for derived classes to inherit from. A class can inherit from only one abstract class.

Interface: An interface is a contract that defines a set of methods and properties. It only contains method signatures, properties, events, and indexers. It cannot have fields or constructors. A class can implement multiple interfaces, enabling multiple inheritance of behavior.


How to implement multiple inheritance in C#?

C# does not support multiple inheritance of classes, but you can achieve a similar effect using interfaces. By implementing multiple interfaces, a class can inherit and define the behavior of each interface. Here's an example:

public interface IInterface1

{

    void Method1();

}

public interface IInterface2

{

    void Method2();

}

public class MyClass : IInterface1, IInterface2

{

    public void Method1()

    {

        // Implementation

    }

    public void Method2()

    {

        // Implementation

    }

}


What is an abstract class?

An abstract class is a class that cannot be instantiated directly and is intended to serve as a base for other classes to inherit from. It can contain abstract and non-abstract members. Abstract members do not have an implementation in the abstract class and must be implemented in derived classes. An abstract class is declared using the `abstract` keyword.


Can you create an object of an abstract class? Why?

No, you cannot create an object of an abstract class. Abstract classes are incomplete and contain one or more abstract members without implementation. They are designed to be inherited by derived classes, which provide implementations for abstract members. Attempting to instantiate an abstract class directly would result in a compilation error.


Difference between abstraction and abstract class?

Abstraction is a broader concept that refers to the process of hiding unnecessary details and exposing only essential features to the user. It allows users to work with high-level concepts without worrying about the underlying implementation.

An abstract class is a specific implementation in object-oriented programming that allows creating classes with both defined and undefined


What is polymorphism?

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type. It enables code to be written that can work with objects of multiple classes, providing flexibility and extensibility. Polymorphism can be achieved through method overriding and method overloading.


What is runtime polymorphism?

Runtime polymorphism, also known as dynamic polymorphism, occurs when the appropriate method implementation is determined at runtime based on the actual type of the object. It is achieved through method overriding, where a derived class provides its own implementation of a method defined in the base class. The decision of which implementation to execute is made dynamically during program execution.


What is method overriding?

Method overriding is a feature in object-oriented programming that allows a subclass to provide its own implementation of a method that is already defined in its superclass. The overridden method in the subclass must have the same name, return type, and parameter list as the method in the superclass. It allows for the specialization of behavior in derived classes.


Keywords in method overriding include:

  • `override`: Used in the derived class to indicate that a method is intended to override a method in the base class.
  • `base`: Used within the derived class to refer to the base class implementation of the overridden method.

Method overriding is applicable to classes that have an inheritance relationship, where the derived class extends or inherits from the base class.


Main objects in ADO.NET?

In ADO.NET (ActiveX Data Objects for .NET), the main objects include:

  • Connection: Represents a connection to a data source.
  • Command: Represents an SQL statement or a stored procedure to execute against a data source.
  • DataReader: Provides a fast, forward-only, read-only stream of data from a data source.
  • DataSet: Represents an in-memory cache of data, which can contain multiple DataTable objects.
  • DataTable: Represents a table of data in memory, consisting of rows and columns.
  • DataAdapter: Serves as a bridge between a DataSet and a data source, enabling data retrieval and update operations.


Difference between DataSet and DataTable?

DataSet: A DataSet is an in-memory cache of data that can hold multiple DataTable objects along with their relationships. It represents a disconnected set of data and can persist its contents in XML format. It can hold data from multiple tables and can be used for offline data manipulation and synchronization.

DataTable: A DataTable represents a single table of data within a DataSet. It consists of rows and columns and is similar to a table in a relational database. It stores data in a tabular form and provides methods and properties for data manipulation and querying.


What are all the different types of execute methods in ADO.NET?

In ADO.NET, the different types of execute methods commonly used are:

  • `ExecuteNonQuery()`: Executes a command that does not return any result set, such as an INSERT, UPDATE, DELETE, or DDL statement.
  • `ExecuteScalar()`: Executes a command and returns the value of the first column of the first row in the result set. Useful when a single value is expected as the result.
  • `ExecuteReader()`: Executes a command and returns a DataReader object for retrieving a forward-only, read-only stream of data.
  • `ExecuteXmlReader()`: Executes a command and returns an XMLReader object for reading XML data from the result set.


Difference between ExecuteScalar and ExecuteNonQuery?

`ExecuteScalar()`: It is used to execute a command and return the value of the first column of the first row in the result set. It is typically used when a single value is expected as the result, such as retrieving a count or an aggregated value. It returns an object that needs to be cast to the appropriate type.

`ExecuteNonQuery()`: It is used to execute a command that does not return any result set, such as INSERT, UPDATE, DELETE, or DDL statements. It returns the number of rows affected by the command.


What is the usage of DataView in C#?

A DataView in C# is a customized view of a DataTable that allows sorting, filtering, and searching the data in various ways. It provides a dynamic and flexible way to present and manipulate data from a DataTable. DataView can be used to apply sorting and filtering conditions to a DataTable, and it also supports data binding with UI controls for efficient data presentation and manipulation.


Types of authentication in SQL?

In SQL, the common types of authentication include:

Windows Authentication: Uses the credentials of the currently logged-in Windows user to authenticate and authorize access to the SQL Server. It relies on Windows security and Active Directory.

SQL Server Authentication: Requires a username and password specific to SQL Server. It does not rely on Windows security but instead maintains its own set of user accounts and passwords.


Write a connection string

The connection string is used to establish a connection to a data source. Here's an example of a connection string for SQL Server using Windows Authentication:

string connectionString = "Data Source=myServerAddress;Initial  Catalog=myDatabase;Integrated Security=True;";

Replace `myServerAddress` with the address of the SQL Server and `myDatabase` with the name of the database you want to connect to.


Types of constraints in SQL?

In SQL, the common types of constraints are:

  • Primary Key: A primary key constraint ensures that a column or a combination of columns uniquely identifies each row in a table.
  • Unique: A unique constraint ensures that the values in a column or a combination of columns are unique across the table.
  • Foreign Key: A foreign key constraint establishes a relationship between two tables by enforcing referential integrity. It ensures that values in a column match values in another table's primary key.
  • Check: A check constraint validates the values in a column to meet a specific condition or range of values.
  • Not Null: A not null constraint ensures that a column does not contain any null values.
  • Default: A default constraint provides a default value for a column if no value is specified during an insert operation.


Queries under DML?

DML (Data Manipulation Language) in SQL is used to modify and retrieve data from tables. Common DML queries include:

  • SELECT: Retrieves data from one or more tables based on specified conditions.
  • INSERT: Inserts new rows of data into a table.
  • UPDATE: Modifies existing data in one or more rows of a table.
  • DELETE: Removes one or more rows of data from a table.


Difference between primary key and unique key?

The primary key and unique key are both used to enforce uniqueness in SQL, but they have some differences:

Primary Key: It uniquely identifies each row in a table and ensures that the identified column(s) have unique values. It is a combination of the unique and not null constraints. Only one primary key can be defined per table.

Unique Key: It ensures that the identified column(s) have unique values. Unlike a primary key, a table can have multiple unique keys. Unique keys can allow null values, except for the columns defined as the primary key.


Can we use multiple primary keys?

No, a table can have only one primary key. The primary key uniquely identifies each row in a table. However, you can use composite primary keys by combining two or more columns to create a unique identifier for a row.


What constraint do you use to check some condition?

To check a condition, you can use the CHECK constraint in SQL. The CHECK constraint allows you to specify a condition that must be satisfied for each row in a table. If the condition evaluates to false, the constraint prevents the insertion or modification of the row.


Difference between DELETE and TRUNCATE?

The DELETE and TRUNCATE statements are used to remove data from tables in SQL, but they differ in their behavior:

DELETE: The DELETE statement is a DML statement that removes specific rows from a table based on specified conditions. It provides more flexibility by allowing you to specify complex filtering criteria. DELETE operation can be rolled back using a transaction.

TRUNCATE: The TRUNCATE statement is a DDL statement that removes all rows from a table. It is faster than DELETE because it does not generate individual undo logs for each deleted row. TRUNCATE operation cannot be rolled back as it is considered a non-logged operation.


Tell me a TRUNCATE query.

The TRUNCATE query is used to remove all rows from a table. The syntax for TRUNCATE is as follows:

TRUNCATE TABLE table_name;

Replace `table_name` with the name of the table you want to truncate. Be cautious when using TRUNCATE as it permanently deletes all data from the table.


How to filter particular department data from a textfile table?

To filter particular department data from a textfile table, you can use the SQL SELECT statement with a

 WHERE clause. Assuming you have a column named 'department' in your textfile table, the query would be:

SELECT * FROM textfile_table WHERE department = 'desired_department';

Replace `textfile_table` with the name of your table and `'desired_department'` with the specific department you want to filter.


How to find duplicate data from a table?

To find duplicate data in a table, you can use the SQL SELECT statement with the GROUP BY and HAVING clauses. Here's an example:

SELECT column1, column2, COUNT(*) as count

FROM your_table

GROUP BY column1, column2

HAVING COUNT(*) > 1;

Replace `your_table` with the name of your table and specify the column(s) you want to check for duplicates in the SELECT, GROUP BY, and HAVING clauses.


Usage of knowledge?

The term "knowledge" is quite broad, but in the context of software development and programming, knowledge refers to the understanding and expertise in various programming languages, frameworks, algorithms, design patterns, and best practices. Having knowledge in these areas allows developers to effectively analyze problems, design efficient solutions, and write high-quality code. Knowledge is acquired through learning, experience, and continuous self-improvement, and it is essential for building robust and scalable software systems.


Write a query to rename a column in a table?

To rename a column in a table, you can use the ALTER TABLE statement with the RENAME COLUMN clause. Here's an example:

ALTER TABLE your_table

RENAME COLUMN old_column_name TO new_column_name;

Replace `your_table` with the name of your table, `old_column_name` with the current name of the column you want to rename, and `new_column_name` with the desired new name for the column.


How to change the data type of a particular column in a table?

To change the data type of a column in a table, you can use the ALTER TABLE statement with the ALTER COLUMN clause. Here's an example:

ALTER TABLE your_table

ALTER COLUMN your_column_name NEW_DATA_TYPE;

Replace `your_table` with the name of your table, `your_column_name` with the name of the column you want to change the data type of, and `NEW_DATA_TYPE` with the desired new data type for the column.


How to give auto-generated fields?

To give auto-generated fields, you can use identity columns or sequences in SQL. Identity columns automatically generate incrementing numeric values for each new row inserted into a table. Sequences generate a sequence of numeric values. The specific syntax for implementing auto-generated fields may vary depending on the database system you are using.


Difference between stored procedure and function?

The main differences between stored procedures and functions are:

  • Purpose: A stored procedure is primarily used to perform an action or a series of actions, such as modifying data, executing complex logic, or generating reports. A function is designed to return a single value or a table of values.
  • Return Type: A stored procedure does not have a mandatory return type. It can return zero or more result sets or output parameters. A function has a defined return type and must return a value or a table of values.
  • Usage in Queries: A stored procedure can be invoked from within a query or used as a standalone statement. A function is typically used within a query as part of an expression or a select statement.
  • Transaction Control: A stored procedure can initiate and control transactions. It can include transaction management statements like BEGIN TRANSACTION, COMMIT, and ROLLBACK. A function cannot initiate or control transactions.


How to use exception handling in functions?

In SQL, exception handling in functions is limited compared to stored procedures. Functions can only handle exceptions related to user-defined errors using the `TRY...CATCH` construct. Here's an example:

CREATE FUNCTION your_function

(

    -- Function parameters

)

RETURNS data_type

AS

BEGIN

    BEGIN TRY

        -- Function logic

    END TRY

    BEGIN CATCH

        -- Error handling

    END CATCH

    RETURN -- Return statement

END;

Within the `BEGIN TRY` block, you can write your function's logic. If an error occurs, the `BEGIN CATCH` block is executed, allowing you to handle the exception appropriately.


How to handle exceptions in stored procedures?

In SQL, stored procedures provide robust exception handling capabilities using the `TRY...CATCH` construct. Here's an example:

CREATE PROCEDURE your_procedure

(

    -- Procedure parameters

)

AS

BEGIN

    BEGIN TRY

        -- Procedure logic

    END TRY

    BEGIN CATCH

        -- Error handling

    END CATCH

END;

Within the `BEGIN TRY` block, you can write your procedure's logic. If an error occurs, the `BEGIN CATCH` block is executed, allowing you to handle the exception appropriately.


What is a transaction in a stored procedure?

A transaction in a stored procedure is a logical unit of work that consists of one or more database operations. Transactions ensure that all operations within the unit are treated as a single, indivisible entity. They provide the ACID (Atomicity, Consistency, Isolation, Durability) properties to maintain data integrity and consistency. Transactions can be initiated using the `BEGIN TRANSACTION` statement, and changes made within the transaction can be either committed (`COMMIT`) or rolled back (`ROLLBACK`) based on the desired outcome.


Types of functions in SQL?

In SQL, there are several types of functions, including:

  • Scalar Functions: Return a single value based on input parameters.
  • Table-Valued Functions: Return a table as a result, allowing multiple rows and columns to be returned.
  • Aggregate Functions: Perform calculations on a set of values and return a single value, such as SUM, AVG, COUNT, MIN, MAX, etc.
  • String Functions: Manipulate and operate on string values, such as CONCAT, SUBSTRING, LEN, etc.
  • Date and Time Functions: Perform operations on date and time values, such as GETDATE, DATEPART, DATEADD, etc.


What are the built-in aggregate functions in SQL Server?

SQL Server provides several built-in aggregate functions, including:

  • SUM: Calculates the sum of a set of values.
  • AVG: Calculates the average of a set of values.
  • COUNT: Counts the number of rows or non-null values in a set.
  • MIN: Retrieves the minimum value from a set.
  • MAX: Retrieves the maximum value from a set.


Built-in string functions in SQL Server?

SQL Server provides various built-in string functions, including:

  • CONCAT: Concatenates two or more strings together.
  • SUBSTRING: Extracts a portion of a string.
  • LEN: Returns the length of a string.
  • UPPER: Converts a string to uppercase.
  • LOWER: Converts a string to lowercase.
  • REPLACE: Replaces occurrences of a specified string with another string.


What is SQL Profiler?

SQL Profiler is a tool provided by Microsoft SQL Server that allows you to monitor and capture events occurring in a SQL Server database. It provides a graphical interface to trace and analyze database activities, including queries, stored procedure executions, errors, and performance-related information. SQL Profiler is useful for debugging, optimizing queries, troubleshooting, and auditing database activities.


How to create an index in SQL Server?

To create an index in SQL Server, you can use the CREATE INDEX statement. Here's an example:

CREATE INDEX index_name

ON your_table (column1, column2, ...);

Replace `index_name` with the desired name for the index, `your_table` with the name of your table, and `column1`, `column2`, etc., with the columns you want to include in the index. Indexes improve query performance by allowing faster data retrieval based on the indexed columns.


Types of joins in SQL Server?

In SQL Server, the common types of joins are:

  • INNER JOIN: Returns rows that have matching values in both tables.
  • LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table and matching rows from the right table.
  • RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table and matching rows from the left table.
  • FULL JOIN (or FULL OUTER JOIN): Returns all rows from both tables, with NULL values for non-matching rows.
  • CROSS JOIN: Returns the Cartesian product of both tables (all possible combinations of rows).


Difference between left outer join and right outer join?

The main difference between a left outer join and a right outer join is the tables from which the non-matching rows are retrieved:

  • Left Outer Join: Retrieves all rows from the left (or first) table and the matching rows from the right (or second) table. Non-matching rows from the right table will have NULL values in the result set.
  • Right Outer Join: Retrieves all rows from the right (or second) table and the matching rows from the left (or first) table. Non-matching rows from the left table will have NULL values in the result set.

The choice between left and right outer join depends on the desired output and the relationship between the tables.


In what situation do you use a self-join?

A self-join is used when a table needs to be joined with itself based on a relationship between two columns within the same table. It is commonly used when working with hierarchical data or when you need to compare rows within the same table.

For example, consider a table that stores employee information, where each row contains an employee ID and a manager ID that references another employee in the same table. By performing a self-join on the employee ID and manager ID columns, you can retrieve information about employees and their respective managers.


How to improve the performance of an existing stored procedure?

To improve the performance of an existing stored procedure, you can consider the following approaches:

  • Optimize Query Logic: Review the SQL statements within the stored procedure and ensure they are efficient. Use appropriate indexes, avoid unnecessary joins or subqueries, and optimize WHERE clauses.
  • Use Proper Indexing: Analyze the execution plan of the stored procedure and identify missing or inefficient indexes. Create indexes on columns used in join conditions, WHERE clauses, or ORDER BY clauses.
  • Minimize Data Retrieval: Retrieve only the necessary columns and rows instead of fetching all data. Use appropriate filtering conditions and limit the result set size.
  • Re-evaluate Cursors: If your stored procedure uses cursors, consider alternative approaches like set-based operations to improve performance.
  • Regularly Update Statistics: Keep the statistics of the database up to date to ensure the query optimizer has accurate information for generating efficient execution plans.
  • Consider Stored Procedure Recompilation: In some cases, forcing a stored procedure to recompile can help improve performance. This can be done using the `WITH RECOMPILE` option.


Types of triggers in SQL?

In SQL, there are two types of triggers:

  • DML Triggers: These triggers are fired in response to data manipulation language (DML) events, such as INSERT, UPDATE, and DELETE statements on a table.
  • DDL Triggers: These triggers are fired in response to data definition language (DDL) events, such as CREATE, ALTER, and DROP statements on a database or table.

Triggers allow you to define custom actions or validations that are automatically executed when specific events occur.


Which one is faster between stored procedures and functions? How?

Stored procedures are generally faster than functions because they are precompiled and cached by the database server. When a stored procedure is executed, the execution plan is already compiled, resulting in faster execution.

Functions, on the other hand, need to be evaluated for each row or record being processed. This can lead to additional overhead and slower performance, especially when functions are used in queries that involve large datasets.

However, it's important to note that the actual performance can vary depending on the specific scenario, the complexity of the logic, the amount of data being processed, and other factors. It's recommended to benchmark and analyze the performance of both stored procedures and functions in your specific environment to determine the optimal choice.


How to create a view?

To create a view in SQL, you can use the CREATE VIEW statement. Here's an example:

CREATE VIEW your_view_name AS

SELECT column1, column2, ...

FROM your_table

WHERE condition;

Replace `your_view_name` with the desired name for the view, `column1`, `column2`, etc., with the columns you want to include in the view, `your_table` with the name of the table you want to create the view from, and `condition` with any desired filtering condition.

A view is a virtual table that is based on the result of a SELECT statement. It allows you to simplify complex queries, provide a layer of abstraction, and present a subset of data to users or applications.


Best Dotnet Training