You are on page 1of 71

Keys

o Keys play an important role in the relational database.


o It is used to uniquely identify any record or row of data from the table. It is also used to establish
and identify relationships between tables.

For example, ID is used as a key in the Student table because it is unique for each student. In the
PERSON table, passport_number, license_number, SSN are keys since they are unique for each person.

Types of keys:

1. Primary key
o It is the first key used to identify one and only one instance of an entity uniquely. An entity can contain
multiple keys, as we saw in the PERSON table. The key which is most suitable from those lists becomes a
primary key.
o In the EMPLOYEE table, ID can be the primary key since it is unique for each employee. In the EMPLOYEE
table, we can even select License_Number and Passport_Number as primary keys since they are also
unique.
o For each entity, the primary key selection is based on requirements and developers.
2. Candidate key
o A candidate key is an attribute or set of attributes that can uniquely identify a tuple.
o Except for the primary key, the remaining attributes are considered a candidate key. The candidate keys
are as strong as the primary key.

For example: In the EMPLOYEE table, id is best suited for the primary key. The rest of the attributes,
like SSN, Passport_Number, License_Number, etc., are considered a candidate key.

3. Super Key
Super key is an attribute set that can uniquely identify a tuple. A super key is a superset of a candidate
key.
For example: In the above EMPLOYEE table, for(EMPLOEE_ID, EMPLOYEE_NAME), the name of two
employees can be the same, but their EMPLYEE_ID can't be the same. Hence, this combination can also
be a key.

The super key would be EMPLOYEE-ID (EMPLOYEE_ID, EMPLOYEE-NAME), etc.

4. Foreign key
o Foreign keys are the column of the table used to point to the primary key of another table.
o Every employee works in a specific department in a company, and employee and department are two
different entities. So we can't store the department's information in the employee table. That's why we
link these two tables through the primary key of one table.
o We add the primary key of the DEPARTMENT table, Department_Id, as a new attribute in the EMPLOYEE
table.
o In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are related.
5. Alternate key
There may be one or more attributes or a combination of attributes that uniquely identify each tuple in
a relation. These attributes or combinations of the attributes are called the candidate keys. One key is
chosen as the primary key from these candidate keys, and the remaining candidate key, if it exists, is
termed the alternate key. In other words, the total number of the alternate keys is the total number of
candidate keys minus the primary key. The alternate key may or may not exist. If there is only one
candidate key in a relation, it does not have an alternate key.

For example, employee relation has two attributes, Employee_Id and PAN_No, that act as candidate
keys. In this relation, Employee_Id is chosen as the primary key, so the other candidate key, PAN_No,
acts as the Alternate key.

6. Composite key
Whenever a primary key consists of more than one attribute, it is known as a composite key. This key is
also known as Concatenated Key.

For example, in employee relations, we assume that an employee may be assigned multiple roles, and
an employee may work on multiple projects simultaneously. So the primary key will be composed of all
three attributes, namely Emp_ID, Emp_role, and Proj_ID in combination. So these attributes act as a
composite key since the primary key comprises more than one attribute.

7. Artificial key
The key created using arbitrarily assigned data are known as artificial keys. These keys are created when
a primary key is large and complex and has no relationship with many other relations. The data values
of the artificial keys are usually numbered in a serial order.

For example, the primary key, which is composed of Emp_ID, Emp_role, and Proj_ID, is large in
employee relations. So it would be better to add a new virtual attribute to identify each tuple in the
relation uniquely.
SQL Interview Questions and Answers

The following are the most popular and useful SQL interview questions and answers for fresher and
experienced candidates. These questions are created specifically to familiarise you with the types of
questions you might encounter during your SQL interview. According to our experiences, good
interviewers rarely plan to ask any specific topic during the interview. Instead, questioning usually
begins with a basic understanding of the subject, and based on your responses, further discussion
happened.

1) What is SQL?
SQL stands for the Structured Query Language. It is the standard language used to maintain the
relational database and perform many different data manipulation operations on the data. SQL was
initially invented in 1970. It is a database language used for database creation, deletion, fetching and
modifying rows, etc. sometimes, it is pronounced as 'sequel.' We can also use it to handle organized
data comprised of entities (variables) and relations between different entities of the data.

2) When SQL appeared?


SQL first appeared in 1974. It is one of the most used languages for maintaining the relational database.
In 1986, SQL became the standard of the American National Standards Institute (ANSI) and ISO
(International Organization for Standardization) in 1987.

3) What are the usages of SQL?


SQL is responsible for maintaining the relational data and the data structures present in the database.
Some of the common usages are given below:

o To execute queries against a database


o To retrieve data from a database
o To inserts records in a database
o To updates records in a database
o To delete records from a database
o To create new databases
o To create new tables in a database
o To create views in a database
o To perform complex operations on the database.

4) Does SQL support programming language features?


SQL refers to the Standard Query Language. Therefore, it is true that SQL is a language but does not
actually support the programming language. It is a common language that doesn't have a loop,
conditional statements, and logical operations. It cannot be used for anything other than data
manipulation. It is a command language to perform database operations. The primary purpose of SQL
is to retrieve, manipulate, update, delete, and perform complex operations like joins on the data present
in the database.

5) What are the subsets of SQL?


The following are the four significant subsets of the SQL:

o Data definition language (DDL): It defines the data structure that consists of commands like CREATE,
ALTER, DROP, etc.
o Data manipulation language (DML): It is used to manipulate existing data in the database. The
commands in this category are SELECT, UPDATE, INSERT, etc.
o Data control language (DCL): It controls access to the data stored in the database. The commands in
this category include GRANT and REVOKE.
o Transaction Control Language (TCL): It is used to deal with the transaction operations in the database.
The commands in this category are COMMIT, ROLLBACK, SET TRANSACTION, SAVEPOINT, etc.

AD

6) What is the purpose of DDL Language?


DDL stands for Data definition language. It is the subset of a database that defines the data structure
of the database when the database is created. For example, we can use the DDL commands to add,
remove, or modify tables. It consists of the following commands: CREATE, ALTER and DELETE database
objects such as schema, tables, indexes, view, sequence, etc.
Example

1. CREATE TABLE Students


2. (
3. Roll_no INT,
4. Name VARCHAR(45),
5. Branch VARCHAR(30),
6. );

7) What is the purpose of DML Language?


Data manipulation language makes the user able to retrieve and manipulate data in a relational
database. The DML commands can only perform read-only operations on data. We can perform the
following operations using DDL language:

o Insert data into the database through the INSERT command.


o Retrieve data from the database through the SELECT command.
o Update data in the database through the UPDATE command.
o Delete data from the database through the DELETE command.

Example

1. INSERT INTO Student VALUES (111, 'George', 'Computer Science')

8) What is the purpose of DCL Language?


Data control language allows users to control access and permission management to the database. It
is the subset of a database, which decides that what part of the database should be accessed by which
user at what point of time. It includes two commands, GRANT and REVOKE.

GRANT: It enables system administrators to assign privileges and roles to the specific user accounts to
perform specific tasks on the database.

REVOKE: It enables system administrators to revoke privileges and roles from the user accounts so that
they cannot use the previously assigned permission on the database.

Example

1. GRANT * ON mydb.Student TO javatpoint@localhsot;


9) What are tables and fields in the database?
A table is a set of organized data in the form of rows and columns. It enables users to store and display
records in the structure format. It is similar to worksheets in the spreadsheet application. Here rows
refer to the tuples, representing the simple data item, and columns are the attribute of the data items
present in a particular row. Columns can categorize as vertical, and Rows are horizontal.

Fields are the components to provide the structure for the table. It stores the same category of data in
the same data type. A table contains a fixed number of columns but can have any number of rows
known as the record. It is also called a column in the table of the database. It represents the attribute
or characteristics of the entity in the record.

Example

Table: Student

Field: Stud_rollno, Stud_name, Date of Birth, Branch, etc.

10) What is a primary key?


A primary key is a field or the combination of fields that uniquely identify each record in the table. It is
one of a special kind of unique key. If the column contains a primary key, it cannot be null or empty. A
table can have duplicate columns, but it cannot have more than one primary key. It always stores unique
values into a column. For example, the ROLL Number can be treated as the primary key for a student
in the university or college.

We can define a primary key into a student table as follows:

1. CREATE TABLE Student (


2. roll_number INT PRIMARY KEY,
3. name VARCHAR(45),
4. );

To read more information, click here.

AD
11) What is a foreign key?
The foreign key is used to link one or more tables together. It is also known as the referencing key. A
foreign key is specified as a key that is related to the primary key of another table. It means a foreign
key field in one table refers to the primary key field of the other table. It identifies each row of another
table uniquely that maintains the referential integrity. The primary key-foreign key relationship is a very
crucial relationship as it maintains the ACID properties of the database sometimes. It also prevents
actions that would destroy links between the child and parent tables.

We can define a foreign key into a table as follows:

1. CONSTRAINT constraint_name]
2. FOREIGN KEY [foreign_key_name] (col_name, ...)
3. REFERENCES parent_tbl_name (col_name,...)

To read more information, click here.

12) What is a unique key?


A unique key is a single or combination of fields that ensure all values stores in the column will be
unique. It means a column cannot stores duplicate values. This key provides uniqueness for the column
or set of columns. For example, the email addresses and roll numbers of student's tables should be
unique. It can accept a null value but only one null value per column. It ensures the integrity of the
column or group of columns to store different values into a table.

We can define a foreign key into a table as follows:

1. CREATE TABLE table_name(


2. col1 datatype,
3. col2 datatype UNIQUE,
4. ...
5. );

To read more information, click here.

13) What is the difference between a primary key and a unique key?
The primary key and unique key both are essential constraints of the SQL. The main difference among
them is that the primary key identifies each record in the table. In contrast, the unique key prevents
duplicate entries in a column except for a NULL value. The following comparison chart explains it more
clearly:

Primary Key Unique Key

The primary key act as a unique identifier for each record in the The unique key is also a unique identifier for record
table. table.

We cannot store NULL values in the primary key column. We can store NULL value in the unique key column

We cannot change or delete the primary key column values. We can modify the unique key column values.

To read more information, click here.

14) What is a Database?


A database is an organized collection of data that is structured into tables, rows, columns, and indexes.
It helps the user to find the relevant information frequently. It is an electronic system that makes data
access, data manipulation, data retrieval, data storing, and data management very easy. Almost every
organization uses the database for storing the data due to its easily accessible and high operational
ease. The database provides perfect access to data and lets us perform required tasks.

The following are the common features of a database:

o Manages large amounts of data


o Accurate
o Easy to update
o Security
o Data integrity
o Easy to research data

15) What is meant by DBMS?


DBMS stands for Database Management System. It is a software program that primarily functions as an
interface between the database and the end-user. It provides us the power such as managing the data,
the database engine, and the database schema to facilitate the organization and manipulation of data
using a simple query in almost no time. It is like a File Manager that manages data in a database rather
than saving it in file systems. Without the database management system, it would be far more difficult
for the user to access the database's data.

The following are the components of a DBMS:

o Software
o Data
o Procedures
o Database Languages
o Query Processor
o Database Manager
o Database Engine
o Reporting

16) What are the different types of database management systems?


The database management systems can be categorized into several types. Some of the important lists
are given below:

o Hierarchical databases (DBMS)


o Network databases (IDMS)
o Relational databases (RDBMS
o Object-oriented databases
o Document databases (Document DB)
o Graph databases
o ER model databases
o NoSQL databases

17) What is RDBMS?


RDBMS stands for Relational Database Management System. It is a database management system
based on a relational model. It facilitates you to manipulate the data stored in the tables by using
relational operators. RDBMS stores the data into the collection of tables and links those tables using
the relational operators easily whenever required. Examples of relational database management
systems are Microsoft Access, MySQL, SQL Server, Oracle database, etc.
18) What is Normalization in a Database?
Normalization is used to minimize redundancy and dependency by organizing fields and table of a
database.

There are some rules of database normalization, which is commonly known as Normal From, and they
are:

o First normal form(1NF)


o Second normal form(2NF)
o Third normal form(3NF)
o Boyce-Codd normal form(BCNF)

Using these steps, the redundancy, anomalies, inconsistency of the data in the database can be
removed.

19) What is the primary use of Normalization?


Normalization is mainly used to add, delete or modify a field that can be made in a single table. The
primary use of Normalization is to remove redundancy and remove the insert, delete and update
distractions. Normalization breaks the table into small partitions and then links them using different
relationships to avoid the chances of redundancy.

20) What are the disadvantages of not performing database


Normalization?
The major disadvantages are:

The occurrence of redundant terms in the database causes the waste of space in the disk.

Due to redundant terms, inconsistency may also occur. If any change is made in the data of one table
but not made in the same data of another table, then inconsistency will occur. This inconsistency will
lead to the maintenance problem and effects the ACID properties as well.

21) What is an inconsistent dependency?


An Inconsistent dependency refers to the difficulty of getting relevant data due to a missing or broken
path to the data. It leads users to search the data in the wrong table, resulting in an error as an output.
22) What is Denormalization in a Database?
Denormalization is a technique used by database administrators to optimize the efficiency of their
database infrastructure. The denormalization concept is based on Normalization, which is defined as
arranging a database into tables correctly for a particular purpose. This method allows us to add
redundant data into a normalized database to alleviate issues with database queries that merge data
from several tables into a single table. It adds redundant terms into the tables to avoid complex joins
and many other complex operations.

Denormalization doesn't mean that normalization will not be done. It is an optimization strategy that
takes place after the normalization process.

23) What are the different types of SQL operators?


Operators are the special keywords or special characters reserved for performing particular operations.
They are also used in SQL queries. We can primarily use these operators within the WHERE clause of
SQL commands. It's a part of the command to filters data based on the specified condition. The SQL
operators can be categorized into the following types:

o Arithmetic operators: These operators are used to perform mathematical operations on numerical data.
The categories of this operators are addition (+), subtraction (-), multiplication (*), division (/),
remainder/modulus (%), etc.
o Logical operators: These operators evaluate the expressions and return their results in True or False. This
operator includes ALL, AND, ANY, ISNULL, EXISTS, BETWEEN, IN, LIKE, NOT, OR, UNIQUE.
o Comparison operators: These operators are used to perform comparisons of two values and check
whether they are the same or not. It includes equal to (=), not equal to (!= or <>), less than (<), greater
than (>), less than or equal to (<=), greater than or equal to (>=), not less than (!<), not greater than (!>),
etc.
o Bitwise operators: It is used to do bit manipulations between two expressions of integer type. It first
performs conversion of integers into binary bits and then applied operators such as AND (& symbol), OR
(|, ^), NOT (~), etc.
o Compound operators: These operators perform operations on a variable before setting the variable's
result to the operation's result. It includes Add equals (+=), subtract equals (-=), multiply equals (*=),
divide equals (/=), modulo equals (%=), etc.
o String operators: These operators are primarily used to perform concatenation and pattern matching of
strings. It includes + (String concatenation), += (String concatenation assignment), % (Wildcard), []
(Character(s) matches), [^] (Character(s) not to match), _ (Wildcard match one character), etc.
24) What is a view in SQL?
A view is a database object that has no values. It is a virtual table that contains a subset of data within
a table. It looks like an actual table containing rows and columns, but it takes less space because it is
not present physically. It is operated similarly to the base table but does not contain any data of its own.
Its name is always unique. A view can have data from one or more tables. If any changes occur in the
underlying table, the same changes reflected in the views also.

The primary use of a view is to implement the security mechanism. It is the searchable object where we
can use a query to search the view as we use for the table. It only shows the data returned by the query
that was declared when the view was created.

We can create a view by using the following syntax:

1. CREATE VIEW view_name AS


2. SELECT column_lists FROM table_name
3. WHERE condition;

25) What is an Index in SQL?


An index is a disc structure associated with a table or view that speeds up row retrieval. It reduces the
cost of the query because the query's high cost will lead to a fall in its performance. It is used to increase
the performance and allow faster retrieval of records from the table. Indexing reduces the number of
data pages we need to visit to find a particular data page. It also has a unique value meaning that the
index cannot be duplicated. An index creates an entry for each value which makes it faster to retrieve
data.
For example: Suppose we have a book which carries the details of the countries. If you want to find
out information about India, why will you go through every page of that book? You could directly go
to the index. Then from the index, you can go to that particular page where all the information about
India is given.

26) What are the different types of indexes in SQL?


SQL indexes are nothing more than a technique of minimizing the query's cost. The higher the query's
cost, the worse the query's performance. The following are the different types of Indexes supported in
SQL:

o Unique Index
o Clustered Index
o Non-Clustered Index
o Bit-Map Index
o Normal Index
o Composite Index
o B-Tree Index
o Function-Based Index

27) What is the unique index?


UNIQUE INDEX is used to enforce the uniqueness of values in single or multiple columns. We can create
more than one unique index in a single table. For creating a unique index, the user has to check the
data in the column because the unique indexes are used when any column of the table has unique
values. This indexing does not allow the field to have duplicate values if the column is unique indexed.
A unique index can be applied automatically when a primary key is defined.

We can create it by using the following syntax:

1. CREATE UNIQUE INDEX index_name


2. ON table_name (index_column1, index_column2,...);

Example

1. CREATE TABLE Employee(


2. ID int AUTO_INCREMENT PRIMARY KEY,
3. Name varchar(45),
4. Phone varchar(15),
5. City varchar(25),
6. );

Suppose we want to make a Phone column as a unique index. We can do this like below:

1. CREATE UNIQUE INDEX index_name_phone ON Employee (Phone);

To read more information, click here.

28) What is clustered index in SQL?


A clustered index is actually a table where the data for the rows are stored. It determines the order of
the table data based on the key values that can sort in only one direction. Each table can have only one
clustered index. It is the only index, which has been automatically created when the primary key is
generated. If many data modifications needed to be done in the table, then clustered indexes are
preferred.

To read more information, click here.

29) What is the non-clustered index in SQL?


The indexes other than PRIMARY indexes (clustered indexes) are called non-clustered indexes. We know
that clustered indexes are created automatically when primary keys are generated, and non-clustered
indexes are created when multiple joins conditions and various filters are used in the query. The non-
clustered index and table data are both stored in different places. It cannot be able to alter the physical
order of the table and maintains the logical order of data.

The purpose of creating a non-clustered index is for searching the data. Its best example is a book
where the content is written in one place, and the index is at a different place. We can create 0 to 249
non-clustered indexes in each table. The non-clustered indexing improves the performance of the
queries which use keys without assigning the primary key.

30) What are the differences between SQL, MySQL, and SQL Server?
The following comparison chart explains their main differences:

SQL MySQL SQL Ser


SQL or Structured Query Language is useful for MySQL is the popular database management system SQL Serv
managing our relational databases. It is used to used for managing the relational database. It is a fast, develope
query and operate the database. scalable, and easy-to-use database. and acces

SQL first appeared in 1974. MySQL first appeared on May 23, 1995. SQL Serve

SQL was developed by IBM Corporation. MySQL was developed by Oracle Corporation. SQL Serve

SQL is a query language for managing databases. MySQL is database software that uses SQL language SQL Serve
to conduct with the database. to condu

SQL has no variables. MySQL can use variables constraints and data types. SQL Serv
types.

SQL is a programming language, so that it does MySQL is software, so it gets frequent updation. SQL Serv
not get any updates. Its commands are always updation
fixed and remain the same.

31) What is the difference between SQL and PL/SQL?


The following comparison chart explains their main differences:

SQL PL/SQL

SQL is a database structured query language used to communicate PL/SQL or Procedural Language/Structured Q
with relational databases. It was developed by IBM Corporations and enhance the capabilities of SQL. Oracle Corpo
first appeared in 1974. SQL as its database language.

SQL is a declarative and data-oriented language. PL/SQL is a procedural and application-oriente

SQL has no variables. PL/SQL can use variables constraints and data t

SQL can execute only a single query at a time. PL/SQL can execute a whole block of code at o

SQL query can be embedded in PL/SQL. PL/SQL cannot be embedded in SQL as SQL do
and keywords.

SQL can directly interact with the database server. PL/SQL cannot directly interact with the databa
SQL is like the source of data that we need to display. PL/SQL provides a platform where SQL data wi

32) Is it possible to sort a column using a column alias?


Yes. We can use the alias method in the ORDER BY instead of the WHERE clause for sorting a column.

33) What is the difference between clustered and non-clustered indexes


in SQL?
Indexing is a method to get the requested data very fast. There are mainly two types of indexes in SQL,
clustered index and non-clustered index. The differences between these two indexes are very important
from an SQL performance perspective. The following comparison chart explains their main differences:

Clustered Index Non-Clustered Index

A clustered index is a table or view where the data for the rows are stored. In a The indexes other than PRIMARY
relational database, if the table column contains a primary key, MySQL clustered indexes. It has a structu
automatically creates a clustered index named PRIMARY. clustered indexes are also known a

Clustered indexes store the data information and the data itself. Non-clustered indexes stores only
the data stored in clustered data.

There can only be one clustered index per table. There can be one or more non-clus

A clustered index determines how data is stored physically in the table. Therefore, It creates a logical ordering of dat
reading from a clustered index is faster. physical data files. Therefore, readi

A clustered index always contains an index id of 0. A non-clustered index always conta

To read more information, click here.

34) What is the SQL query to display the current date?


There is a built-in function in SQL called GetDate(), which is used to return the current timestamp.
35) Which are joins in SQL? Name the most commonly used SQL joins?
SQL joins are used to retrieve data from multiple tables into a meaningful result set. It is performed
whenever you need to fetch records from two or more tables. They are used with SELECT statement
and join conditions.

The following are the most commonly used joins in SQL:

o INNER JOIN
o LEFT OUTER JOIN
o RIGHT OUTER JOIN

36) What are the different types of joins in SQL?


Joins are used to merge two tables or retrieve data from tables. It depends on the relationship between
tables. According to the ANSI standard, the following are the different types of joins used in SQL:

o INNER JOIN
o SELF JOIN
o LEFT OUTER JOIN
o RIGHT OUTER JOIN
o FULL OUTER JOIN
o CROSS JOIN

To read more information, click here.


37) What is INNER JOIN in SQL?
Inner join returns only those records from the tables that match the specified condition and hides other
rows and columns. In simple words, it fetches rows when there is at least one match of rows between
the tables is found. INNER JOIN keyword joins the matching records from two tables. It is assumed as
a default join, so it is optional to use the INNER keyword with the query.

The below visual representation explain this join more clearly:

The following syntax illustrates the INNER JOIN:

1. SELECT column_lists
2. FROM table1
3. INNER JOIN table2 ON join_condition1
4. INNER JOIN table3 ON join_condition2
5. ...;

To read more information, click here.

38) What is the Right JOIN in SQL?


The Right join is used to retrieve all rows from the right-hand table and only those rows from the other
table that fulfilled the join condition. It returns all the rows from the right-hand side table even though
there are no matches in the left-hand side table. If it finds unmatched records from the left side table,
it returns a Null value. This join is also known as Right Outer Join.
The below visual representation explain this join more clearly:

The following syntax illustrates the RIGHT JOIN:

1. SELECT colum_lists
2. FROM table1
3. RIGHT JOIN table2
4. ON join_condition;

To read more information, click here.

39) What is Left Join in SQL?


The Left Join is used to fetch all rows from the left-hand table and common records between the
specified tables. It returns all the rows from the left-hand side table even though there are no matches
on the right-hand side table. If it will not find any matching record from the right side table, then it
returns null. This join can also be called a Left Outer Join.

The following visual representation explains it more clearly:


The following syntax illustrates the RIGHT JOIN:

1. SELECT colum_lists
2. FROM table1
3. LEFT JOIN table2
4. ON join_condition;

To read more information, click here.

40) What is Full Join in SQL?


The Full Join results from a combination of both left and right join that contains all the records from
both tables. It fetches rows when there are matching rows in any one of the tables. This means it returns
all the rows from the left-hand side table and all the rows from the right-hand side tables. If a match is
not found, it puts NULL value. It is also known as FULL OUTER JOIN.

The following visual representation explains it more clearly:


The following syntax illustrates the FULL JOIN:

1. SELECT * FROM table1


2. FULL OUTER JOIN table2
3. ON join_condition;

To read more information, click here.

41) What is a "TRIGGER" in SQL?


A trigger is a set of SQL statements that reside in a system catalog. It is a special type of stored
procedure that is invoked automatically in response to an event. It allows us to execute a batch of code
when an insert, update or delete command is run against a specific table because the trigger is the set
of activated actions whenever DML commands are given to the system.

SQL triggers have two main components one is action, and another is an event. When certain actions
are taken, an event occurs as a result of those actions.

We use the CREATE TRIGGER statement for creating a trigger in SQL. Here is the syntax:

1. CREATE TRIGGER trigger_name


2. (AFTER | BEFORE) (INSERT | UPDATE | DELETE)
3. ON table_name FOR EACH ROW
4. BEGIN
5. --variable declarations
6. --trigger code
7. END;
To read more information, click here.

42) What is self-join and what is the requirement of self-join?


A SELF JOIN is used to join a table with itself. This join can be performed using table aliases, which allow
us to avoid repeating the same table name in a single sentence. It will throw an error if we use the same
table name more than once in a single query without using table aliases.

A SELF JOIN is required when we want to combine data with other data in the same table itself. It is
often very useful to convert a hierarchical structure to a flat structure.

The following syntax illustrates the SELF JOIN:

1. SELECT column_lists
2. FROM table1 AS T1, table1 AS T2
3. WHERE join_conditions;

Example

Suppose we have a table 'Student' having the following data:

If we want to get retrieve the student_id and name from the table where student_id is equal, and
course_id is not equal, it can be done by using the self-join:

1. SELECT s1.student_id, s1.name


2. FROM student AS s1, student s2
3. WHERE s1.student_id=s2.student_id
4. AND s1.course_id<>s2.course_id;

Here is the result:

To read more information, click here.


43) What are the set operators in SQL?
We use the set operators to merge data from one or more tables of the same kind. Although the set
operators are like SQL joins, there is a significant distinction. SQL joins combine columns from separate
tables, whereas SQL set operators combine rows from different queries. SQL queries that contain set
operations are called compound queries. The set operators in SQL are categories into four different
types:

A. UNION: It combines two or more results from multiple SELECT queries into a single result set. It has
a default feature to remove the duplicate rows from the tables. The following syntax illustrates the
Union operator:

1. SELECT columns FROM table1


2. UNION
3. SELECT columns FROM table2;

B. UNION ALL: This operator is similar to the Union operator, but it does not remove the duplicate
rows from the output of the SELECT statements. The following syntax illustrates the UNION ALL
operator:

1. SELECT columns FROM table1


2. UNION ALL
3. SELECT columns FROM table2;

C. INTERSECT: This operator returns the common records from two or more SELECT statements. It
always retrieves unique records and arranges them in ascending order by default. Here, the number of
columns and data types should be the same. The following syntax illustrates the INTERSECT operator:
1. SELECT columns FROM table1
2. INTERSECT
3. SELECT columns FROM table2;

D. MINUS: This operator returns the records from the first query, which is not found in the second
query. It does not return duplicate values. The following syntax illustrates the MINUS operator:

1. SELECT columns FROM table1


2. MINUS
3. SELECT columns FROM table2;

To read more information, click here.

44) What is the difference between IN and BETWEEN operators?


The following comparison chart explains their main differences:

BETWEEN Operator IN Operator

This operator is used to selects the range of data between two values. It is a logical operator to determine whether o
The values can be numbers, text, and dates as well. values. This operator reduces the use of multipl

It returns records whose column value lies in between the defined It compares the specified column's value and r
range. the set of values.

The following syntax illustrates this operator: The following syntax


SELECT * FROM table_name SELECT *
WHERE column_name BETWEEN 'value1' AND 'value2'; WHERE column_name IN ('value1','value 2');

45) What is a constraint? Tell me about its various levels.


The constraint is used to specify the rule and regulations that allows or restricts what values/data will
be stored in the table. It ensures data accuracy and integrity inside the table. It enforces us to store
valid data and prevents us from storing irrelevant data. If any interruption occurs between the constraint
and data action, the action is failed. Some of the most commonly used constraints are NOT NULL,
PRIMARY KEY, FOREIGN KEY, AUTO_INCREMENT, UNIQUE KEY, etc.

The following syntax illustrates us to create a constraint for a table:

1. CREATE TABLE table_name (


2. column1 datatype constraint,
3. column2 datatype constraint,
4. .........
5. );

SQL categories the constraints into two levels:

Column Level Constraints: These constraints are only applied to a single column and limit the type of
data that can be stored in that column.

Table Level Constraints: These constraints are applied to the entire table and limit the type of data
that can be entered.

To read more information, click here.

46) How to write an SQL query to find students' names start with 'A'?
We can write the following query to get the student details whose name starts with A:

1. SELECT * FROM student WHERE stud_name like 'A%';

Here is the demo example where we have a table named student that contains two names starting with
the 'A' character.
47) Write the SQL query to get the third maximum salary of an employee
from a table named employees.
The following query is the simplest way to get the third maximum salary of an employee:

1. SELECT * FROM `employees` ORDER BY `salary` DESC LIMIT 1 OFFSET 2

Here is the demo example that shows how to get the third maximum salary of an employee.

The following are the alternative way to get the third-highest salary of an employee:

A. Using LIMIT Keyword

1. SELECT salary FROM employees


2. ORDER BY salary DESC
3. LIMIT 2, 1;

B. Using Subquery

1. SELECT salary
2. FROM
3. (SELECT salary
4. FROM employees
5. ORDER BY salary DESC
6. LIMIT 3) AS Temp
7. ORDER BY salary LIMIT 1;

C. Using TOP Keyword

1. SELECT TOP 1 salary


2. FROM
3. (SELECT DISTINCT TOP 3 salary
4. FROM employees
5. ORDER BY salary DESC) AS Temp
6. ORDER BY salary ASC;

48) What is the difference between DELETE and TRUNCATE statements


in SQL?
The main difference between them is that the delete statement deletes data without resetting a table's
identity, whereas the truncate command resets a particular table's identity. The following comparison
chart explains it more clearly:

No. DELETE TRUNCATE

1) The delete statement removes single or multiple rows from an existing The truncate command deletes the wh
table depending on the specified condition. table itself. It preserves the table stru

2) DELETE is a DML command. TRUNCATE is a DML command.

3) We can use the WHERE clause in the DELETE command. We cannot use the WHERE clause w

4) DELETE statement is used to delete a row from a table. TRUNCATE statement is used to rem

5) DELETE is slower because it maintained the log. TRUNCATE statement is faster than D
a time without maintaining transactio

6) You can roll back data after using the DELETE statement. It is not possible to roll back after u

7) DELETE query takes more space. TRUNCATE query occupies less spac

To read more information, click here.


49) What is the ACID property in a database?
The ACID properties are meant for the transaction that goes through a different group of tasks. A
transaction is a single logical order of data. It provides properties to maintain consistency before and
after the transaction in a database. It also ensures that the data transactions are processed reliably in a
database system.

The ACID property is an acronym for Atomicity, Consistency, Isolation, and Durability.

Atomicity: It ensures that all statements or operations within the transaction unit must be executed
successfully. If one part of the transaction fails, the entire transaction fails, and the database state is left
unchanged. Its main features are COMMIT, ROLLBACK, and AUTO-COMMIT.

Consistency: This property ensures that the data must meet all validation rules. In simple words, we
can say that the database changes state only when a transaction will be committed successfully. It also
protects data from crashes.

Isolation: This property guarantees that the concurrent property of execution in the transaction unit
must be operated independently. It also ensures that statements are transparent to each other. The
main goal of providing isolation is to control concurrency in a database.

Durability: This property guarantees that once a transaction has been committed, it persists
permanently even if the system crashes, power loss, or failed.

To read more information, click here.

50) Is a blank space or zero the same as a NULL value?


No. The NULL value is not the same as zero or a blank space. The following points explain their main
differences:

o A NULL value is a value, which is 'unavailable, unassigned, unknown or not applicable.' It would be used
in the absence of any value. We can perform arithmetic operations on it. On the other hand, zero is a
number, and a blank space is treated as a character.
o The NULL value can be treated as an unknown and missing value, but zero and blank spaces differ from
the NULL value.
o We can compare a blank space or a zero to another blank space or a zero. On the other hand, one NULL
may not be the same as another NULL. NULL indicates that no data has been provided or that no data
exists.
51) What are functions and their usage in SQL?
SQL functions are simple code snippets that are frequently used and re-used in database systems for
data processing and manipulation. Functions are the measured values. It always performs a specific
task. The following rules should be remembered while creating functions:

o A function should have a name, and the name cannot begin with a special character such as @, $, #, or
other similar characters.
o Functions can only work with the SELECT statements.
o Every time a function is called, it compiles.
o Functions must return value or result.
o Functions are always used with input parameters.

SQL categories the functions into two types:

o User-Defined Function: Functions created by a user based on their needs are termed user-defined
functions.
o System Defined Function: Functions whose definition is defined by the system are termed system-
defined functions. They are built-in database functions.

SQL functions are used for the following purposes:

o To perform calculations on data


o To modify individual data items
o To manipulate the output
o To format dates and numbers
o To convert data types

52) What is meant by case manipulation functions? Explains its


different types in SQL.
Case manipulation functions are part of the character functions. It converts the data from the state in
which it is already stored in the table to upper, lower, or mixed case. The conversion performed by this
function can be used to format the output. We can use it in almost every part of the SQL statement.
Case manipulation functions are mostly used when you need to search for data, and you don't have
any idea that the data you are looking for is in lower case or upper case.

There are three case manipulation functions in SQL:


LOWER: This function is used to converts a given character into lowercase. The following example will
return the 'STEPHEN' as 'stephen':

1. SELECT LOWER ('STEPHEN') AS Case_Reault FROM dual;


NOTE: Here, 'dual' is a dummy table.

UPPER: This function is used to converts a given character into uppercase. The following example will
return the 'stephen' as 'STEPHEN':

1. SELECT UPPER ('stephen') AS Case_Reault FROM dual;

INITCAP: This function is used to converts given character values to uppercase for the initials of each
word. It means every first letter of the word is converted into uppercase, and the rest is in lower case.
The following example will return the 'hello stephen' as 'Hello Stephen':

1. SELECT INITCAP ('hello stephen') AS Case_Reault FROM dual;

53) Explain character-manipulation functions? Explains its different


types in SQL.
Character-manipulation functions are used to change, extract, and alter the character string. When one
or more characters and words are passed into the function, the function will perform its operation on
those input strings and return the result.

The following are the character manipulation functions in SQL:

A) CONCAT: This function is used to join two or more values together. It always appends the second
string into the end of the first string. For example:

Input: SELECT CONCAT ('Information-', 'technology') FROM DUAL;

Output: Information-technology

B) SUBSTR: It is used to return the portion of the string from a specified start point to an endpoint. For
example:

Input: SELECT SUBSTR ('Database Management System', 9, 11) FROM DUAL;

Output: Management

C) LENGTH: This function returns the string's length in numerical value, including the blank spaces. For
example:

Input: SELECT LENGTH ('Hello Javatpoint') FROM DUAL;


Output: 16

D) INSTR: This function finds the exact numeric position of a specified character or word in a given
string. For example:

Input: SELECT INSTR ('Hello Javatpoint', 'Javatpoint');

Output: 7

E) LPAD: It returns the padding of the left-side character value for right-justified value. For example:

Input: SELECT LPAD ('200', 6,'*');

Output: ***200

F) RPAD: It returns the padding of the right-side character value for left-justified value. For example:

Input: SELECT RPAD ('200', 6,'*');

Output: 200***

G) TRIM: This function is used to remove all the defined characters from the beginning, end, or both.
It also trimmed extra spaces. For example:

Input: SELECT TRIM ('A' FROM 'ABCDCBA');

Output: BCDCB

H) REPLACE: This function is used to replace all occurrences of a word or portion of the string
(substring) with the other specified string value. For example:

Input: SELECT REPLACE ( 'It is the best coffee at the famous coffee shop.', 'coffee', 'tea');

Output: It is the best tea at the famous tea shop.

54) What is the usage of the NVL() function?


The NVL() function is used to convert the NULL value to the other value. The function returns the value
of the second parameter if the first parameter is NULL. If the first parameter is anything other than
NULL, it is left unchanged. This function is used in Oracle, not in SQL and MySQL. Instead of NVL()
function, MySQL have IFNULL() and SQL Server have ISNULL() function.
55) Which function is used to return remainder in a division operator in
SQL?
The MOD function returns the remainder in a division operation.

56) What are the syntax and use of the COALESCE function?
The COALESCE() function evaluates the arguments in sequence and returns the first NON-NULL value
in a specified number of expressions. If it evaluates arguments as NULL or not found any NON-NULL
value, it returns the NULL result.

The syntax of COALESCE function is given below:

1. COALESCE (exp1, exp2, .... expn)

Example:

1. SELECT COALESCE(NULL, 'Hello', 'Javatpoint', NULL) AS Result;

This statement will return the following output:

57) How do we use the DISTINCT statement? What is its use?


The DISTINCT keyword is used to ensure that the fetched value always has unique values. It does not
allow to have duplicate values. The DISTINCT keyword is used with the SELECT statement and retrieves
different values from the table's column. We can use it with the help of the following syntax:

1. SELECT DISTINCT column_lists FROM table_name WHERE [condition];

Suppose we have a table 'customer' containing eight records in which the name column has some
duplicate values.
If we want to get the name column without any duplicate values, the DISTINCT keyword is required.
Executing the below command will return a name column with unique values.

58) What is the default ordering of data using the ORDER BY clause?
How could it be changed?
The ORDER BY clause is used to sort the table data either in ascending or descending order. By default,
it will sort the table in ascending order. If we want to change its default behavior, we need to use the
DESC keyword after the column name in the ORDER BY clause.

The syntax to do this is given below:

1. SELECT expressions FROM tables


2. WHERE conditions
3. ORDER BY expression [ASC | DESC];

We have taken a customer table in the previous example. Now, we will demonstrate the ORDER BY
clause on them as well.

In the below output, we can see that the first query will sort the table data in ascending order based on
the name column. However, if we run the second query by specifying the DESC keyword, the table's
order is changed in descending order.
59) Is the following query returns the output?
1. SELECT subject_code, AVG (marks)
2. FROM Students
3. WHERE AVG(marks) > 70
4. GROUP BY subject_code;

Answer: No. The above query does not return the output because we cannot use the WHERE clause to
restrict the groups. We need to use the HAVING clause instead of the WHERE clause to get the correct
output.

60) What is the difference between the WHERE and HAVING clauses?
The main difference is that the WHERE clause is used to filter records before any groupings are
established, whereas the HAVING clause is used to filter values from a group. The below comparison
chart explains the most common differences:
WHERE HAVING

This clause is implemented in row operations. This clause is implement

It does not allow to work with aggregate functions. It can work with aggrega

This clause can be used with the SELECT, UPDATE, and DELETE statements. This clause can only be u

To know more differences, click here.

61) How many Aggregate functions are available in SQL?


The aggregate function is used to determine and calculate several values in a table and return the result
as a single number. For example, the average of all values, the sum of all values, and the maximum and
minimum value among particular groupings of values.

The following syntax illustrates how to use aggregate functions:

1. function_name (DISTINCT | ALL expression)

SQL provides seven (7) aggregate functions, which are given below:

o AVG(): This function is used to returns the average value from specified columns.
o COUNT(): This function is used to returns the number of table rows, including rows with null values.
o MAX(): This function is used to returns the largest value among the group.
o MIN(): This function is used to returns the smallest value among the group.
o SUM(): This function is used to returns the total summed values(non-null) of the specified column.
o FIRST(): This function is used to returns the first value of an expression.
o LAST(): This function is used to returns the last value of an expression.

62) What is SQL Injection?


SQL injection is a type of vulnerability in website and web app code that allows attackers to control
back-end operations and access, retrieve, and destroy sensitive data from databases. In this technique,
malicious SQL statements are inserted into a database entry field, and once they are performed, the
database becomes vulnerable to an attacker. This technique is commonly used to access sensitive data
and perform administrative activities on databases by exploiting data-driven applications. It is also
known as SQLi attack.
Some common examples of SQL injection are:

o Accessing confidential data to modify an SQL query to get desired results.


o UNION attacks to steal data from different database tables.
o Examine the database to extract information regarding the version and structure of the database.

63) What is the difference between the RANK() and DENSE_RANK()


functions?
The RANK function determines the rank for each row within your ordered partition in the result set. If
the two rows are assigned the same rank, then the next number in the ranking will be its previous rank
plus a number of duplicate numbers. For example, if we have three records at rank 4, the next rank
listed would be ranked 7.

The DENSE_RANK function assigns a unique rank for each row within a partition as per the specified
column value without any gaps. It always specifies ranking in consecutive order. If the two rows are
assigned the same rank, this function will assign it with the same rank, and the next rank being the next
sequential number. For example, if we have 3 records at rank 4, the next rank listed would be ranked 5.

64) Is it possible to implicitly insert a row for the identity column?


Yes. We can implicitly insert a row for the identity column. Here is an example of doing this:

1. SET IDENTITY_INSERT TABLE1 ON


2. INSERT INTO demo_table1 (id, name, branch)
3. SELECT id, name, branch FROM demo_table2
4. SET IDENTITY_INSERT OFF

65) What are SQL comments?


Comments are explanations or annotations in SQL queries that are readable by programmers. It's used
to make SQL statements easier to understand for humans. During the parsing of SQL code, it will be
ignored. Comments can be written on a single line or across several lines.

o Single Line Comments: It starts with two consecutive hyphens (--).


o Multi-line Comments: It starts with /* and ends with */.
DBMS Interview Questions
A list of top frequently asked DBMS interview questions and answers are given below.

1) What is DBMS?
DBMS is a collection of programs that facilitates users to create and maintain a database. In other words,
DBMS provides us an interface or tool for performing different operations such as the creation of a
database, inserting data into it, deleting data from it, updating the data, etc. DBMS is a software in
which data is stored in a more secure way as compared to the file-based system. Using DBMS, we can
overcome many problems such as- data redundancy, data inconsistency, easy access, more organized
and understandable, and so on. There is the name of some popular Database Management System-
MySQL, Oracle, SQL Server, Amazon simple DB (Cloud-based), etc.

Working of DBMS is defined in the figure below.

2) What is a database?
A Database is a logical, consistent and organized collection of data that it can easily be accessed,
managed and updated. Databases, also known as electronic databases are structured to provide the
facility of creation, insertion, updating of the data efficiently and are stored in the form of a file or set
of files, on the magnetic disk, tapes and another sort of secondary devices. Database mostly consists of
the objects (tables), and tables include of the records and fields. Fields are the basic units of data
storage, which contain the information about a particular aspect or attribute of the entity described by
the database. DBMS is used for extraction of data from the database in the form of the queries.

For more information: Click here

3) What is a database system?


The collection of database and DBMS software together is known as a database system. Through the
database system, we can perform many activities such as-

The data can be stored in the database with ease, and there are no issues of data redundancy and data
inconsistency.
The data will be extracted from the database using DBMS software whenever required. So, the
combination of database and DBMS software enables one to store, retrieve and access data with
considerate accuracy and security.

4) What are the advantages of DBMS?


o Redundancy control
o Restriction for unauthorized access
o Provides multiple user interfaces
o Provides backup and recovery
o Enforces integrity constraints
o Ensure data consistency
o Easy accessibility
o Easy data extraction and data processing due to the use of queries

For more information: Click here

5) What is a checkpoint in DBMS?


The Checkpoint is a type of mechanism where all the previous logs are removed from the system and
permanently stored in the storage disk.

There are two ways which can help the DBMS in recovering and maintaining the ACID properties, and
they are- maintaining the log of each transaction and maintaining shadow pages. So, when it comes to
log based recovery system, checkpoints come into existence. Checkpoints are those points to which the
database engine can recover after a crash as a specified minimal point from where the transaction log
record can be used to recover all the committed data up to the point of the crash.

6) When does checkpoint occur in DBMS?


A checkpoint is like a snapshot of the DBMS state. Using checkpoints, the DBMS can reduce the amount
of work to be done during a restart in the event of subsequent crashes. Checkpoints are used for the
recovery of the database after the system crash. Checkpoints are used in the log-based recovery system.
When due to a system crash we need to restart the system then at that point we use checkpoints. So
that, we don't have to perform the transactions from the very starting.
7) What do you mean by transparent DBMS?
The transparent DBMS is a type of DBMS which keeps its physical structure hidden from users. Physical
structure or physical storage structure implies to the memory manager of the DBMS, and it describes
how the data stored on disk.

8) What are the unary operations in Relational Algebra?


PROJECTION and SELECTION are the unary operations in relational algebra. Unary operations are those
operations which use single operands. Unary operations are SELECTION, PROJECTION, and RENAME.

As in SELECTION relational operators are used for example - =,<=,>=, etc.

9) What is RDBMS?
RDBMS stands for Relational Database Management Systems. It is used to maintain the data records
and indices in tables. RDBMS is the form of DBMS which uses the structure to identify and access data
concerning the other piece of data in the database. RDBMS is the system that enables you to perform
different operations such as- update, insert, delete, manipulate and administer a relational database
with minimal difficulties. Most of the time RDBMS use SQL language because it is easily understandable
and is used for often.

10) How many types of database languages are?


There are four types of database languages:

o Data Definition Language (DDL) e.g., CREATE, ALTER, DROP, TRUNCATE, RENAME, etc. All these
commands are used for updating the data that?s why they are known as Data Definition Language.
o Data Manipulation Language (DML) e.g., SELECT, UPDATE, INSERT, DELETE, etc. These commands are
used for the manipulation of already updated data that's why they are the part of Data Manipulation
Language.
o DATA Control Language (DCL) e.g., GRANT and REVOKE. These commands are used for giving and
removing the user access on the database. So, they are the part of Data Control Language.
o Transaction Control Language (TCL) e.g., COMMIT, ROLLBACK, and SAVEPOINT. These are the
commands used for managing transactions in the database. TCL is used for managing the changes made
by DML.

AD
Database language implies the queries that are used for the update, modify and manipulate the data.

11) What do you understand by Data Model?


The Data model is specified as a collection of conceptual tools for describing data, data relationships,
data semantics and constraints. These models are used to describe the relationship between the entities
and their attributes.

There is the number of data models:

o Hierarchical data model


o network model
o relational model
o Entity-Relationship model and so on.

12) Define a Relation Schema and a Relation.


A Relation Schema is specified as a set of attributes. It is also known as table schema. It defines what
the name of the table is. Relation schema is known as the blueprint with the help of which we can
explain that how the data is organized into tables. This blueprint contains no data.

A relation is specified as a set of tuples. A relation is the set of related attributes with identifying key
attributes

AD

See this example:

Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values
t=(v1,v2, ...., vn).

13) What is a degree of Relation?


The degree of relation is a number of attribute of its relation schema. A degree of relation is also known
as Cardinality it is defined as the number of occurrence of one entity which is connected to the number
of occurrence of other entity. There are three degree of relation they are one-to-one(1:1), one-to-
many(1:M), many-to-one(M:M).
14) What is the Relationship?
The Relationship is defined as an association among two or more entities. There are three type of
relationships in DBMS-

One-To-One: Here one record of any object can be related to one record of another object.

One-To-Many (many-to-one): Here one record of any object can be related to many records of other
object and vice versa.

Many-to-many: Here more than one records of an object can be related to n number of records of
another object.

15) What are the disadvantages of file processing systems?


o Inconsistent
o Not secure
o Data redundancy
o Difficult in accessing data
o Data isolation
o Data integrity
o Concurrent access is not possible
o Limited data sharing
o Atomicity problem

16) What is data abstraction in DBMS?


Data abstraction in DBMS is a process of hiding irrelevant details from users. Because database systems
are made of complex data structures so, it makes accessible the user interaction with the database.

For example: We know that most of the users prefer those systems which have a simple GUI that means
no complex processing. So, to keep the user tuned and for making the access to the data easy, it is
necessary to do data abstraction. In addition to it, data abstraction divides the system in different layers
to make the work specified and well defined.

17) What are the three levels of data abstraction?


Following are three levels of data abstraction:
Physical level: It is the lowest level of abstraction. It describes how data are stored.

Logical level: It is the next higher level of abstraction. It describes what data are stored in the database
and what the relationship among those data is.

View level: It is the highest level of data abstraction. It describes only part of the entire database.

For example- User interacts with the system using the GUI and fill the required details, but the user
doesn't have any idea how the data is being used. So, the abstraction level is entirely high in VIEW
LEVEL.

Then, the next level is for PROGRAMMERS as in this level the fields and records are visible and the
programmers have the knowledge of this layer. So, the level of abstraction here is a little low in VIEW
LEVEL.

And lastly, physical level in which storage blocks are described.

18) What is DDL (Data Definition Language)?


Data Definition Language (DDL) is a standard for commands which defines the different structures in a
database. Most commonly DDL statements are CREATE, ALTER, and DROP. These commands are used
for updating data into the database.

19) What is DML (Data Manipulation Language)?


DData Manipulation Language (DML) is a language that enables the user to access or manipulate data
as organized by the appropriate data model. For example- SELECT, UPDATE, INSERT, DELETE.

There is two type of DML:

Procedural DML or Low level DML: It requires a user to specify what data are needed and how to get
those data.

Non-Procedural DML or High level DML:It requires a user to specify what data are needed without
specifying how to get those data.

20) Explain the functionality of DML Compiler.


The DML Compiler translates DML statements in a query language that the query evaluation engine
can understand. DML Compiler is required because the DML is the family of syntax element which is
very similar to the other programming language which requires compilation. So, it is essential to
compile the code in the language which query evaluation engine can understand and then work on
those queries with proper output.

21) What is Relational Algebra?


Relational Algebra is a Procedural Query Language which contains a set of operations that take one or
two relations as input and produce a new relationship. Relational algebra is the basic set of operations
for the relational model. The decisive point of relational algebra is that it is similar to the algebra which
operates on the number.

There are few fundamental operations of relational algebra:

o select
o project
o set difference
o union
o rename,etc.

22) What is Relational Calculus?


Relational Calculus is a Non-procedural Query Language which uses mathematical predicate calculus
instead of algebra. Relational calculus doesn't work on mathematics fundamentals such as algebra,
differential, integration, etc. That's why it is also known as predicate calculus.

There is two type of relational calculus:

o Tuple relational calculus


o Domain relational calculus

23) What do you understand by query optimization?


The term query optimization specifies an efficient execution plan for evaluating a query that has the
least estimated cost. The concept of query optimization came into the frame when there were a number
of methods, and algorithms existed for the same task then the question arose that which one is more
efficient and the process of determining the efficient way is known as query optimization.

There are many benefits of query optimization:

o It reduces the time and space complexity.


o More queries can be performed as due to optimization every query comparatively takes less time.
o User satisfaction as it will provide output fast

24) What do you mean by durability in DBMS?


Once the DBMS informs the user that a transaction has completed successfully, its effect should persist
even if the system crashes before all its changes are reflected on disk. This property is called durability.
Durability ensures that once the transaction is committed into the database, it will be stored in the non-
volatile memory and after that system failure cannot affect that data anymore.

25) What is normalization?


Normalization is a process of analysing the given relation schemas according to their functional
dependencies. It is used to minimize redundancy and also used to minimize insertion, deletion and
update distractions. Normalization is considered as an essential process as it is used to avoid data
redundancy, insertion anomaly, updation anomaly, deletion anomaly.

There most commonly used normal forms are:

o First Normal Form(1NF)


o Second Normal Form(2NF)
o Third Normal Form(3NF)
o Boyce & Codd Normal Form(BCNF)

26) What is Denormalization?


Denormalization is the process of boosting up database performance and adding of redundant data
which helps to get rid of complex data. Denormalization is a part of database optimization technique.
This process is used to avoid the use of complex and costly joins. Denormalization doesn't refer to the
thought of not to normalize instead of that denormalization takes place after normalization. In this
process, firstly the redundancy of the data will be removed using normalization process than through
denormalization process we will add redundant data as per the requirement so that we can easily avoid
the costly joins.

27) What is functional Dependency?


Functional Dependency is the starting point of normalization. It exists when a relation between two
attributes allow you to determine the corresponding attribute's value uniquely. The functional
dependency is also known as database dependency and defines as the relationship which occurs when
one attribute in a relation uniquely determines another attribute. It is written as A->B which means B is
functionally dependent on A.

28) What is the E-R model?


E-R model is a short name for the Entity-Relationship model. This model is based on the real world. It
contains necessary objects (known as entities) and the relationship among these objects. Here the
primary objects are the entity, attribute of that entity, relationship set, an attribute of that relationship
set can be mapped in the form of E-R diagram.

In E-R diagram, entities are represented by rectangles, relationships are represented by diamonds,
attributes are the characteristics of entities and represented by ellipses, and data flow is represented
through a straight line.

29) What is an entity?


The Entity is a set of attributes in a database. An entity can be a real-world object which physically exists
in this world. All the entities have their attribute which in the real world considered as the characteristics
of the object.

For example: In the employee database of a company, the employee, department, and the designation
can be considered as the entities. These entities have some characteristics which will be the attributes
of the corresponding entity.

30) What is an Entity type?


An entity type is specified as a collection of entities, having the same attributes. Entity type typically
corresponds to one or several related tables in the database. A characteristic or trait which defines or
uniquely identifies the entity is called entity type.

For example, a student has student_id, department, and course as its characteristics.

31) What is an Entity set?


The entity set specifies the collection of all entities of a particular entity type in the database. An entity
set is known as the set of all the entities which share the same properties.

For example, a set of people, a set of students, a set of companies, etc.


32) What is an Extension of entity type?
An extension of an entity type is specified as a collection of entities of a particular entity type that are
grouped into an entity set.

33) What is Weak Entity set?


An entity set that doesn't have sufficient attributes to form a primary key is referred to as a weak entity
set. The member of a weak entity set is known as a subordinate entity. Weak entity set does not have a
primary key, but we need a mean to differentiate among all those entries in the entity set that depend
on one particular strong entity set.

34) What is an attribute?


An attribute refers to a database component. It is used to describe the property of an entity. An attribute
can be defined as the characteristics of the entity. Entities can be uniquely identified using the attributes.
Attributes represent the instances in the row of the database.

For example: If a student is an entity in the table then age will be the attribute of that student.

35) What are the integrity rules in DBMS?


Data integrity is one significant aspect while maintaining the database. So, data integrity is enforced in
the database system by imposing a series of rules. Those set of integrity is known as the integrity rules.

There are two integrity rules in DBMS:

Entity Integrity : It specifies that "Primary key cannot have a NULL value."

Referential Integrity: It specifies that "Foreign Key can be either a NULL value or should be the Primary
Key value of other relation

36) What do you mean by extension and intension?


Extension: The Extension is the number of tuples present in a table at any instance. It changes as the
tuples are created, updated and destroyed. The actual data in the database change quite frequently.
So, the data in the database at a particular moment in time is known as extension or database state or
snapshot. It is time dependent.
Intension: Intension is also known as Data Schema and defined as the description of the database,
which is specified during database design and is expected to remain unchanged. The Intension is a
constant value that gives the name, structure of tables and the constraints laid on it.

37) What is System R? How many of its two major subsystems?


System R was designed and developed from 1974 to 1979 at IBM San Jose Research Centre. System R
is the first implementation of SQL, which is the standard relational data query language, and it was also
the first to demonstrate that RDBMS could provide better transaction processing performance. It is a
prototype which is formed to show that it is possible to build a Relational System that can be used in a
real-life environment to solve real-life problems.

Following are two major subsystems of System R:

o Research Storage
o System Relational Data System

38) What is Data Independence?


Data independence specifies that "the application is independent of the storage structure and access
strategy of data." It makes you able to modify the schema definition at one level without altering the
schema definition in the next higher level.

It makes you able to modify the schema definition in one level should not affect the schema definition
in the next higher level.

There are two types of Data Independence:

Physical Data Independence: Physical data is the data stored in the database. It is in the bit-format.
Modification in physical level should not affect the logical level.

For example: If we want to manipulate the data inside any table that should not change the format of
the table.

Logical Data Independence: Logical data in the data about the database. It basically defines the
structure. Such as tables stored in the database. Modification in logical level should not affect the view
level.

For example: If we need to modify the format of any table, that modification should not affect the data
inside it.

NOTE: Logical Data Independence is more difficult to achieve.


39) What are the three levels of data abstraction?
Following are three levels of data abstraction:

Physical level: It is the lowest level of abstraction. It describes how data are stored.

Logical level: It is the next higher level of abstraction. It describes what data are stored in the database
and what relationship among those data.

View level: It is the highest level of data abstraction. It describes only part of the entire database.

For example- User interact with the system using the GUI and fill the required details, but the user
doesn't have any idea how the data is being used. So, the abstraction level is absolutely high in VIEW
LEVEL.

Then, the next level is for PROGRAMMERS as in this level the fields and records are visible and the
programmer has the knowledge of this layer. So, the level of abstraction here is a little low in VIEW
LEVEL.

And lastly, physical level in which storage blocks are described.

40) What is Join?


The Join operation is one of the most useful activities in relational algebra. It is most commonly used
way to combine information from two or more relations. A Join is always performed on the basis of the
same or related column. Most complex queries of SQL involve JOIN command.

There are following types of join:

o Inner joins: Inner join is of 3 categories. They are:


o Theta join
o Natural join
o Equi join
o Outer joins: Outer join have three types. They are:
o Left outer join
o Right outer join
o Full outer join
41) What is 1NF?
1NF is the First Normal Form. It is the simplest type of normalization that you can implement in a
database. The primary objectives of 1NF are to:

o Every column must have atomic (single value)


o To Remove duplicate columns from the same table
o Create separate tables for each group of related data and identify each row with a unique column

42) What is 2NF?


2NF is the Second Normal Form. A table is said to be 2NF if it follows the following conditions:

o The table is in 1NF, i.e., firstly it is necessary that the table should follow the rules of 1NF.
o Every non-prime attribute is fully functionally dependent on the primary key, i.e., every non-key attribute
should be dependent on the primary key in such a way that if any key element is deleted, then even the
non_key element will still be saved in the database.

43) What is 3NF?


3NF stands for Third Normal Form. A database is called in 3NF if it satisfies the following conditions:

o It is in second normal form.


o There is no transitive functional dependency.
o For example: X->Z

Where:
X->Y
Y does not -> X
Y->Z so, X->Z

44) What is BCNF?


BCMF stands for Boyce-Codd Normal Form. It is an advanced version of 3NF, so it is also referred to
as 3.5NF. BCNF is stricter than 3NF.

A table complies with BCNF if it satisfies the following conditions:

o It is in 3NF.
o For every functional dependency X->Y, X should be the super key of the table. It merely means that X
cannot be a non-prime attribute if Y is a prime attribute.

45) Explain ACID properties


ACID properties are some basic rules, which has to be satisfied by every transaction to preserve the
integrity. These properties and rules are:

ATOMICITY: Atomicity is more generally known as ?all or nothing rule.' Which implies all are
considered as one unit, and they either run to completion or not executed at all.

CONSISTENCY: This property refers to the uniformity of the data. Consistency implies that the database
is consistent before and after the transaction.

ISOLATION: This property states that the number of the transaction can be executed concurrently
without leading to the inconsistency of the database state.

DURABILITY: This property ensures that once the transaction is committed it will be stored in the non-
volatile memory and system crash can also not affect it anymore.

46) What is stored procedure?


A stored procedure is a group of SQL statements that have been created and stored in the database.
The stored procedure increases the reusability as here the code or the procedure is stored into the
system and used again and again that makes the work easy, takes less time in processing and decreases
the complexity of the system. So, if you have a code which you need to use again and again then save
that code and call that code whenever it is required.

47) What is the difference between a DELETE command and TRUNCATE


command?
DELETE command: DELETE command is used to delete rows from a table based on the condition that
we provide in a WHERE clause.

o DELETE command delete only those rows which are specified with the WHERE clause.
o DELETE command can be rolled back.
o DELETE command maintain a log, that's why it is slow.
o DELETE use row lock while performing DELETE function.
TRUNCATE command: TRUNCATE command is used to remove all rows (complete data) from a table.
It is similar to the DELETE command with no WHERE clause.

o The TRUNCATE command removes all the rows from the table.
o The TRUNCATE command cannot be rolled back.
o The TRUNCATE command doesn't maintain a log. That's why it is fast.
o TRUNCATE use table log while performing the TRUNCATE function.

48) What is 2-Tier architecture?


The 2-Tier architecture is the same as basic client-server. In the two-tier architecture, applications on
the client end can directly communicate with the database at the server side.
49) What is the 3-Tier architecture?
The 3-Tier architecture contains another layer between the client and server. Introduction of 3-tier
architecture is for the ease of the users as it provides the GUI, which, make the system secure and much
more accessible. In this architecture, the application on the client-end interacts with an application on
the server which further communicates with the database system.

50) How do you communicate with an RDBMS?


You have to use Structured Query Language (SQL) to communicate with the RDBMS. Using queries of
SQL, we can give the input to the database and then after processing of the queries database will
provide us the required output.
51) What is the difference between a shared lock and exclusive lock?
Shared lock: Shared lock is required for reading a data item. In the shared lock, many transactions may
hold a lock on the same data item. When more than one transaction is allowed to read the data items
then that is known as the shared lock.

Exclusive lock: When any transaction is about to perform the write operation, then the lock on the data
item is an exclusive lock. Because, if we allow more than one transaction then that will lead to the
inconsistency in the database.

52) Describe the types of keys?


There are following types of keys:

Primary key: The Primary key is an attribute in a table that can uniquely identify each record in a table.
It is compulsory for every table.

Candidate key: The Candidate key is an attribute or set of an attribute which can uniquely identify a
tuple. The Primary key can be selected from these attributes.

Super key: The Super key is a set of attributes which can uniquely identify a tuple. Super key is a
superset of the candidate key.

Foreign key: The Foreign key is a primary key from one table, which has a relationship with another
table. It acts as a cross-reference between tables.
SQL Server Interview Questions
A list of top frequently asked SQL Server interview questions and answers are given below.

1) What is SQL Server?


SQL Server is the RDBMS system provided by Microsoft which functions mainly as retrieving and storing
the data as per user request. Sometimes it is mistakenly referred as SQL, but both are different, as SQL
is a language whereas SQL Server is a Microsoft product that supports SQL.

2) What is Normalization?
In RDBMS, the process of organizing data to minimize redundancy and surety of logical data integrity
is called normalization. In normalization, the database is divided into two or more tables, and a
relationship is defined among the tables. Normalization technique increases performance for the
database.

Types of Normalization

There are types of normalization used, which are given below.

o 1NF
o 2NF
o 3NF
o BCNF
o 4NF
o 5NF

However, the first three types are only frequently used, where "NF" stands for normal form. The
originator of the RD model "E.F Codd" has proposed the process "normalization" with the first "normal
form" and continued till third normal form.

3) What is De-Normalization?
It is a process of attempting to optimize the performance of a database by adding redundant data.
Redundancy is introduced intentionally in a table to improve performance, and it is called de-
normalization. The de-Normalization process enhances the read performance while some degradation
occurs in write performance. It can be achieved by making a group of data in the redundant form. The
un-normalized and de-Normalized database are completely different from each other. Before the
process of de-normalization of any database, that should be normalized firstly.
4) What is the difference between function and stored procedure?
o A Function must return a value while stored procedure can return zero or n value.
o Functions can have only input parameter while procedures can have input/ output parameters.
o Functions take one mandatory input parameter while stored procedures may take 0 to n input parameter.
o Try-catch block can handle exceptions. In the stored procedure, while you can't use try-catch in functions.

AD

5) What is collation sensitivity? Explain different types.


Collation sensitivity is used to define the rules for sorting and comparing the strings of character data.
The basic rule for sorting a character data are correct character sequence, Case-sensitivity, character
width, and accent marks, etc.

Different types of collation sensitivity:

o Case sensitivity
o Accent sensitivity
o Kana sensitivity
o Width sensitivity

Case Sensitivity: Case sensitivity defines every character with a unique value, as alphabet characters A
and a are treated individually, as they have different ASCII values for a computer language

Accent sensitivity: Accent sensitivity is related that whether the accent is off or not, as a and á both
should be treated differently

Kana sensitivity: Kana sensitivity defines the difference between two Japanese words: Hiragana and
Katakana

Width sensitivity: It differentiates between a single-byte character (half- width) and representation of
the double-byte character of the same character

6) What is the standby server?


The Standby server is the type of server which is brought online when the primary server goes offline,
and the application needs continuous availability of the server. The requirement for a mechanism which
can shift a primary server to secondary or standby server is always there.

There are three types of standby servers:


Hot standby: Hot standby method is a method of redundancy in which the primary and secondary
backup systems run simultaneously so the data also present in the secondary server in a real-time and
this way both systems contain identical information.

Warm standby: Warm standby is a method of redundancy in which the secondary system runs in the
background of the primary system. Data is mirrored in the secondary server at a regular interval, so in
this method sometimes both servers don't contain the same data.

Cold standby: Cold standby is the method of redundancy in which the secondary server is only called
when the primary server fails. Cold standby systems are used in cases where data is changed
infrequently or for nor critical applications. The physical replacement of Primary server with standby
server occurs in cold standby.

7) What is the difference between clustered and non-clustered index?


Clustered Index: A clustered index is a particular type of index that reorders the way records in the
table are physically stored. It gives a sequence of data which is physically stored in the database.
Therefore a table can have only one clustered index. The leaf nodes of a clustered index contain the
data pages. Index id of the clustered index is 0. So a primary key constraint automatically creates a
clustered index.

Non-clustered Index: A non-clustered index is a particular type of index in which the logical order of
the index does not match the physically stored order of the rows on disk. In non-clustered index data
and indexes are stored in different places. The leaf node of a non-clustered index does not consist of
the data pages. Instead, the leaf nodes contain index rows. Index id of non-clustered indexes is greater
than 0.

8) What is the difference between HAVING CLAUSE and WHERE


CLAUSE in SQL Server?
HAVING Clause: HAVING CLAUSE is used only with the SELECT statement. It is generally used in a
GROUP BY clause in a query.

If GROUP BY is not used, HAVING works like a WHERE clause. HAVING clause can be used with the
aggregate function.

AD

Syntax:

1. SELECT expr1, expr2, expr3..,


2. FROM tables
3. WHERE condition
4. GROUP BY expr1, expr2, expr3..,
5. HAVING condition;

WHERE Clause: The WHERE clause is applied to each row before they become a part of the GROUP BY
function in a query. 'WHERE' clause cannot use with the aggregate function.

Syntax:

1. WHERE condition;

9) What is the recursive stored procedure in SQL Server?


The Recursive stored procedure is defined as a method of problem-solving wherein the solution arrives
repetitively. SQL Server supports recursive stored procedure which calls by itself. It can nest up to 32
levels. It can be called by itself directly or indirectly

There are two ways to achieve recursion in the stored procedure:

o Mutual Recursion: By Using mutually recursive stored procedure, indirect recursion can be achieved
o Chain Recursion: If we extend mutual recursion process then we can achieve chain recursion.

10) What are the advantages of using stored procedures in SQL Server?
A list of advantages of Stored Procedures:

o Stored procedures help in reducing the network traffic and latency. It boosts up the application
performance.
o Stored procedures facilitate the reusability of the code.
o Stored procedures provide better security for data.
o You can encapsulate the logic using stored procedures and change stored procedure code without
affecting clients.
o It is possible to reuse stored procedure execution plans, which are cached in SQL Server's memory. This
reduces server overhead.
o It provides modularity of application.

11) Define the one-to-one relationship while designing tables.


One-to-One relationship: It can be implemented as a single table and rarely as two tables with primary
and foreign key relationships.
One to one relationship exists if an entity in one table has a link with only one entity on another table.
Let?s take an example of the employee and their employee id so that a unique employee id will be
there for a particular employee at another table.

12) How can you hide the SQL Server instances?


You have to make a change in the SQL Server Configuration Manager to hide the SQL Server instances.

Follow the below instructions to launch SQL Server Configuration Manager and do the following:

o Select the instance of SQL Server.


o Right-click and select Properties.
o After selecting properties, you will just set Hide Instance to "Yes" and click OK or Apply.
o After the change is made, you need to restart the instance of SQL Server, not to expose the name of the
instance.

13) What is CHECK constraint in SQL Server?


A CHECK constraint is applied to a column in a table to limit the values that can be placed in a column.
It enforces integrity. After using the check constraint on the single column, we can only give some
specific values for that particular column. Check constraint apply a condition for each column in the
table.

EXAMPLE:

1. CREATE TABLE Employee (


2. EMP_ID int NOT NULL,
3. LastName varchar(255) NOT NULL,
4. FirstName varchar(255),
5. Age int,
6. City varchar(255),
7. CONSTRAINT CHK_Employee CHECK (Age>20AND City= 'Greenville')
8. );

14) What do you mean by SQL Server agent?


The SQL Server agent plays a vital role in day to day tasks of SQL server administrator (DBA). It is one
of the essential parts of the Microsoft's SQL server. Server agent's purpose is to implement the tasks
easily with the scheduler engine which allows our jobs to run at scheduled date and time. SQL server
agent store scheduled administrative tasks information using SQL server.
15) What is COALESCE in SQL Server?
COALESCE is used to return first non-null expression within the arguments. This function is used to
return a non-null from more than one column in the arguments. COALESCE accepts all the values but
it only returns non-null value present in the expression.

Syntax:

1. COALESCE(expr1, expr2, expr3,......,expr n)

16) In which TCP/IP port does SQL Server run? Can it be changed?
SQL Server runs on port 1433. Yes, it can be changed from the network utility TCP/IP properties.

17) What are the authentication modes in SQL Server? How can it be
changed?
Authentication mode is used for authentication of the user in SQL server, and it can be selected at the
time of setup of the database engine.

SQL Server supports two authentication modes: Window authentication mode and mixed mode.

Window authentication mode: This authentication mode is used to connect through a Microsoft NT
4.0 or window 2000 user account. In Windows authentication server take computer's username and
password for authentication purpose. SQL server authentication mode is disabled in this mode.

Mixed mode: It is used to connect with the instance of SQL Server using window authentication or SQL
Server authentication. In SQL server authentication mode a unique username and password are required
for a particular database, as it will not depend on windows account.

18) What is SQL Server Profiler?


Microsoft SQL Server Profiler is a graphical user interface that allows system administrators to monitor
events of the database engine. SQL server profiler trace monitor every event to a file. SQL profiler can
be used for real-time monitoring of data or also for future analysis of data.

You can do the following things with a SQL Server Profiler -

You can create a trace.

You can watch the trace results when the trace runs.
You can store the trace results in a table.

You can find out the bugs in queries and diagnose it.

If it is necessary, you can start, stop, pause and modify the trace results.

19) What is the SQL Server agent?


SQL Server agent is a component of Microsoft SQL Server. It is a background tool of Microsoft SQL
Server, so it runs continuously in the background as a window service. SQL Server agent allows the
database administrator to handles automated tasks and schedules jobs. It runs a window service so can
start automatically when the system boots or you can start it manually.

20) What is "scheduled jobs" or "scheduled tasks"?


Scheduled tasks let you manage the tasks in an automated manner that runs on regular or predictable
cycles. You can schedule administrative tasks and also determine the order in which tasks will run.

21) What is the DBCC command and why is it used?


DBCC stands for database consistency checker. This command is used to check the consistency of the
database. DBCC command help to review and monitoring the maintenance of tables, database, and for
validation of operations done on the database, etc. For example:

DBCC CHECKDB: It makes sure that table in the database and the indexes are correctly linked.

DBCC CHECKALLOC: It checks all pages in the database and makes sure that all are correctly allocated.

DBCC CHECKFILEGROUP: It checks all table file group for any damage.

IF the user executes the above commands, a database snapshot is created through the database engine,
and it continues in the consistent transactional state. After that, It runs the checks against stored
database snapshot, and after the completion of the command, it dropped the snapshot.

22) What command is used to rename the database?


sp_renamedb 'oldname', 'newname';
23) Can SQL Server be linked with other Servers like Oracle?
Yes, it can be linked to any Server. It has OLE-DB provider from Microsoft which allow linking.

24) What is the difference between abstract and interface?


Abstract class:

o It provides a set of rules to implement next class. Rules are provided through abstract methods.
o An Abstract method does not contain any definition.
o When a class contains all functions without the body, it is called as Fully Abstract Class.
o Another class can inherit only one abstract class.

Interface:

o If a class contains all abstract methods, then that class is called Interface.
o Interface support like multiple inheritances.
o An Interface does not contain any implementation
o We can only use public or abstract modifiers.

25) What is the difference between the application object and session
object?
The session object is used to maintain the session of each user. If a user enters into an application, he
gets a session id, and when he leaves application, then the session id is deleted. If he enters again into
the application, he gets a different session id, but for application object, once ad id is generated, it
maintains the whole application.

26) Is there any difference between primary key and unique with the NOT
NULL condition?
There is no difference between primary key and unique key but, a unique key will allow single NULL,
but in the primary key, no NULL is accepted.
27) What is the difference between value type and reference type?
Value type and reference type may be similar regarding declaration syntax and usage, but their
semantics are distinct. Value type and reference type differ with the memory area, where it stored.

The Value type is stored on the stack while reference type is stored on the heap.

The Value type stores real data while reference type stores reference to the data.

Accessing is faster in the value type on comparison to reference type.

The value type can contain null value while reference type can't hold a null value.

The value types are derived from System. Value Type while Reference type is derived from System
Object. Means value type stores a particular value but a reference type stores a reference or address to
the object

String, Object, array are the reference type, as they are stored in heap and dynamic in nature

28) What is the Boxing and Unboxing concept in .net?


Boxing: Implicit conversion of a value type (integer, character, etc.) to a reference type (object) is called
boxing. In boxing process, a value type (which generally stores on the stack) is being allocated on the
heap rather than the stack. Boxing wraps a value inside the object which can be stored in the heap
section.

Example

1. //Boxing the variable i:


2. int i= 56;
3. Object obj=i;

Unboxing: explicit conversion of that same reference type (which is created by boxing process) back to
a value type is known as unboxing. In the unboxing process, a boxed value type is unboxed from the
heap and allocated on the stack.

Example

1. //UNBoxing the variable i:


2. obj=56;
3. i= (int) obj;
29) What is the difference between GET and POST methods?
GET and POST methods are 'form submission' method. Both are used to send the data from client
side to server side. These are some differences between GET and POST method -

In GET method caching is possible while it is not possible in POST method.

Only ASCII character data types are allowed in GET method while in POST method there is no restriction,
it allows binary data also.

In GET method length of the string is restricted while in POST method length of the string is not limited.

Get method is not secured as it can be bookmarked but, post method is secured as it cannot be
bookmarked

Get method is stored in browser history but post method is not stored in browser history

30) What is the Log Shipping?


Log shipping is the process of automating the backup of a database and transaction log file on a primary
database server and then restoring them on a standby server. Many servers support this technique for
maintaining a backup server, such as Microsoft SQL Server, 4D server, MySQL, and PostgreSQL.

The primary purpose of log shipping is to increase database availability just like replication. On each of
secondary database, log backups are applied particularly.

Steps for log shipping process:

o Firstly take a backup of transaction log file on Primary SQL server instance
o Copy the log file on secondary SQL server instance
o Restore the Log backup file onto secondary SQL Server instance

31) What are the different type of replication in SQL Server?


There are three types of replication in SQL Server.

1) Snapshot replication: Snapshot replication distributes data exactly as it appears at a specific


moment. Snapshot replication is the best method for replicating data that changes infrequently.
Snapshot replication is the easiest way to maintain.

2) Transactional replication: Transactional replication is a process of distributing data from publisher


to subscriber. Transactional replication is generally used in the "server to server" environment. It is
appropriate when you want incremental change propagated to the subscriber.
3) Merge replication: Merge replication grouped the data from various sources to a single centralized
database. It is generally used in the server to the client environment. Merge replication is appropriate
when multiple subscribers might update the same data at the various time.

32) Which is the main third-party tool used in SQL Server?


A list of third-party tools used in SQL Server:

o SQL CHECK - Idera: It is used to monitor server activities and memory levels.
o SQL DOC 2 - RedGate: It is used to document the databases.
o SQL Backup 5 - RedGate: It is used to automate the Backup Process.
o SQL Prompt - RedGate: It provides IntelliSense for SQL SERVER 2005/2000.
o Lite Speed 5.0 - Quest Soft: It is used for Backup and Restore.

33) What are the advantages of using third-party tools?


A list of advantages of using third-party tools:

o Third party tools provide faster backups and restore.


o They provide flexible backup and recovery options.
o They provide secure backups with encryption.
o They provide the enterprise view of your backup and recovery environment.
o Easily identify optimal backup settings.
o Visibility into the transaction log and transaction log backups.
o Timeline view of backup history and schedules.
o Recover individual database objects.
o Encapsulate a complete database restore into a single file to speed up restore time.
o When we need to improve upon the functionality that SQL Server offers natively.
o Save time, better information or notification.
o Third party tools can put the backups in a single compressed file to reduce the space and time.

34) What are the different types of collation sensitivity in SQL Server?
There are four types of collation sensitivity in SQL Server:

o Case sensitivity
o Accent sensitivity
o Kana Sensitivity
o Width sensitivity

Explained in detail in Question number 5

35) What are the Hotfixes and Patches in SQL Server?


Hotfixes are small software patches that are applied to live systems. A hotfix is a single, cumulative
package that includes one or more files used to address a problem in a software product.

For example - a software bug

A patch is a program installed in the machine to rectify the problem occurred in the system and ensured
the security of that system. The hotfix is a Kind of Patches provided by the Microsoft.

In Microsoft SQL Server, hotfixes are small patches designed to address specific issues, most commonly
to freshly-discovered security holes. Hotfix response proactively against any bug

36) What is the most common trace flags used with SQL Server?
Trace flag in SQL server sets the specific characteristic of the server. It works as an "IF" condition for the
SQL Server. The most common trace flags used with SQL Server are:

o Deadlock Information: 1204, 1205, 1222


o Network Database files: 1807
o Log Record for Connections: 4013
o Skip Startup Stored Procedures: 4022
o Disable Locking Hints: 8755
o Do Force uniform extent allocations instead of mixed page allocations 1118 (SQL 2005 and 2008).

37) How will you decide the active and passive nodes?
Open Cluster Administrator checks the SQL Server group where you can see the current owner. So the
current owner is the active node, and other nodes are passive. Because at one time only one node can
be active and must be in the passive mode in a two node.
38) What is the use of FLOOR function in SQL Server?
FLOOR function is used to round up a non-integer value to the previous least integer. Floor expression
returns a unique value after rounding down the expression.

SYNTAX:

1. FLOOR (expression)

For example:

FLOOR (7.3)

39) What is the usage of SIGN function?


SIGN function is used to define whether the number specified is Positive, Negative and Zero. This will
return +1,-1 or 0. SIGN function returns the value with its sign.

SYNTAX:

1. SIGN (number)
2.
3. If the number>0, then it will return +1
4. If the number=0, then it will return 0
5. If the number<0, then it will return -1

40) What is sub-query in SQL server? Explain its properties.


In SQL Server, a query within the main query like Select, Update, Insert or Delete, is termed as sub-
query. It is also called as INNER Query.

A subquery can be Added to WHERE clause, the FROM clause, or the SELECT clause.

Some properties of the subqueries are given below:

o A subquery must be enclosed in parenthesis


o A sub-query can add WHERE, GROUP BY, and HAVING CLAUSE but it's optional.
o SELECT clause and a FROM clause must be included a subquery.
o A User can include more than one query
41) How can we delete a table in SQL Server?
A user can delete a TABLE from the database by using SQL Server Management Studio or by Transact-
SQL in SQL Server

Following are the steps for deleting a table using SQL Server Management

o Select a Table(wanted to remove) in object explorer


o Choose DELETE from the shortcut menu by right- click on the table
o Click on the 'yes' to confirm the deletion of the table

42) What are the encryption mechanisms in SQL server?


We can use encryption for security of data in the database in SQL Server. Following are the encryption
mechanism used in SQL server:

o Transact-SQL functions
o Asymmetric keys
o Symmetric keys
o Certificates
o Transparent Data Encryption

43) Define Magic Tables in SQL server?


A Table which is automatically created and managed by SQL server internally to store the inserted,
updated values for any DML (SELECT, DELETE, UPDATE, etc.) operation, is called as Magic tables in SQL
server. The triggers preferably use it.

44) What is CDC in SQL Server?


CDC is termed as "Change Data Capture." It captures the recent activity of INSERT, DELETE, and UPDATE,
which are applied to the SQL Server table. It records the changes made in the SQL server table in a
compatible format.

45) How many types of database relationship in SQL server?


There are three types of relationship exist in SQL server:
o One to One Relationship
o Many to Many relationship
o One to One relationship

You might also like