Thursday, 23 November 2017

SQL SERVER INTERVIEW QUESTIONS PART-3


1) What is SQL?
Structured Query Language (SQL) is a language designed specifically for communicating with databases. SQL is an ANSI (American National Standards Institute) standard.

2) What are the Advantages of SQL?
1. SQL is not a proprietary language used by specific database vendors. Almost every major DBMS supports SQL, so learning this one language will enable programmers to interact with any database like ORACLE, SQL, MYSQL etc.
2. SQL is easy to learn. The statements are all made up of descriptive English words, and there aren't that many of them.
3. SQL is actually a very powerful language and by using its language elements you can perform very complex and sophisticated database operations.

3) What is a field in a database?
A field is an area within a record reserved for a specific piece of data.
Examples: Employee Name, Employee ID, etc.

4) What is a Record in a database?
A record is the collection of values / fields of a specific entity: i.e. an Employee, Salary etc.

5) What is a database transaction?
Database transaction takes database from one consistent state to another. At the end of the transaction the system must be in the prior state if the transaction fails or the status of the system should reflect the successful completion if the transaction goes through.

6) What are properties of a transaction?
Properties of the transaction can be summarized as ACID Properties.
1. Atomicity
A transaction consists of many steps. When all the steps in a transaction get completed, it will get reflected in DB or if any step fails, all the transactions are rolled back.
2. Consistency
The database will move from one consistent state to another, if the transaction succeeds and remain in the original state, if the transaction fails.
3. Isolation
Every transaction should operate as if it is the only transaction in the system.
4. Durability
Once a transaction has completed successfully, the updated rows/records must be available for all other transactions on a permanent basis.

7) What is a Database Lock?
Database lock tells a transaction, if the data item in questions is currently being used by other transactions.

8) What is a Composite Key?
A Composite primary key is a type of candidate key, which represents a set of columns whose values uniquely identity every row in a table.
For example - if "Employee_ID" and "Employee Name" in a table is combined to uniquely identify a row it’s called a Composite Key.

9) What is a Composite Primary Key?
A Composite primary key is a set of columns whose values uniquely identify every row in a table. What it means is that, a table which contains composite primary key will be indexed based on the columns specified in the primary key. This key will be referred in Foreign Key tables.
For example - if the combined effect of columns, "Employee_ID" and "Employee Name" in a table is required to uniquely identify a row, it’s called a Composite Primary Key. In this case, both the columns will be represented as primary key.

10) What is a Foreign Key?
When a "one" table's primary key field is added to a related "many" table in order to create the common field which relates the two tables, it is called a foreign key in the "many" table.
For example, the salary of an employee is stored in salary table. The relation is established via foreign key column “Employee_ID_Ref” which refers “Employee_ID” field in the Employee table.

11) What is a Unique Key?
Unique key is same as primary with the difference being the existence of null. Unique key field allows one value as NULL value.

12) Define SQL Insert Statement?
SQL INSERT statement is used to add rows to a table. For a full row insert, SQL Query should start with “insert into “statement followed by table name and values command, followed by the values that need to be inserted into the table. The insert can be used in several ways:
1. To insert a single complete row.
2. To insert a single partial row.

13) Define SQL Update Statement?
SQL Update is used to update data in a row or set of rows specified in the filter condition.
The basic format of an SQL UPDATE statement is, Update command followed by table to be updated and SET command followed by column names and their new values followed by filter condition that determines which rows should be updated.

14) Define SQL Delete Statement?
SQL Delete is used to delete a row or set of rows specified in the filter condition.
The basic format of an SQL DELETE statement is, DELETE FROM command followed by table name followed by filter condition that determines which rows should be updated.

15) What are tables in SQL?
The table is a collection of record and its information at a single view.

16) Why do we use SQL constraints? Which constraints we can use while creating database in SQL?
Constraints are used to set the rules for all records in the table. If any constraints get violated then it can abort the action that caused it.
Constraints are defined while creating the database itself with CREATE TABLE statement or even after the table is created once with ALTER TABLE statement.
There are 5 major constraints are used in SQL, such as
NOT NULL: That indicates that the column must have some value and cannot be left null
UNIQUE: This constraint is used to ensure that each row and column has unique value and no value is being repeated in any other row or column
PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE constraints such as on one or the combination of more than one columns to identify the particular record with a unique identity.
FOREIGN KEY: It is used to ensure the referential integrity of data in the table and also matches the value in one table with another using Primary Key
CHECK: It is used to ensure whether the value in columns fulfills the specified condition.

17) What are wild cards used in database for Pattern Matching?
SQL Like operator is used for pattern matching. SQL 'Like' command takes more time to process. So before using "like" operator, consider suggestions given below on when and where to
Use wild card search.
1) Don't overuse wild cards. If another search operator will do, use it instead.
2) When you do use wild cards, try not to use them at the beginning of the search pattern, unless absolutely necessary. Search patterns that begin with wild cards are the slowest to process. 
3) Pay careful attention to the placement of the wild card symbols. If they are misplaced, you might not return the data you intended.

18) What is a View?
A view is a virtual table which contains data from one or more tables. Views restrict data access of table by selecting only required values and make complex queries easy.
The views are virtual tables. Unlike tables that contain data, views simply contain queries that dynamically retrieve data when used.

19) What are the advantages of Views?
Views restrict access to the data because the view can display selective columns from the table.
Views can be used to make simple queries to retrieve the results of complicated queries. For example, views can be used to query information from multiple tables without the user knowing. 

20) What are the advantages and disadvantages of views in a database?
Advantages:
1. Views don't store data in a physical location.
2. The view can be used to hide some of the columns from the table.
3. Views can provide Access Restriction, since data insertion, update and deletion is not possible with the view.
Disadvantages:
1. When a table is dropped, associated view become irrelevant.
2. Since the view is created when a query requesting data from view is triggered, it’s a bit slow.
3. When views are created for large tables, it occupies more memory.

21) What are transaction and its controls?
A transaction can be defined as the sequence task that is performed on databases in a logical manner to gain certain results. Operations performed like Creating, updating, deleting records in the database comes from transactions.
In simple word, we can say that a transaction means a group of SQL queries executed on database records.
There are 4 transaction controls such as
· COMMIT: It is used to save all changes made through the transaction
· ROLLBACK: It is used to roll back the transaction such as all changes made by the transaction are reverted back and database remains as before
· SET TRANSACTION: Set the name of transaction
· SAVEPOINT: It is used to set the point from where the transaction is to be rolled back

22) What are properties of the transaction?
Properties of transaction are known as ACID properties, such as
Atomicity: Ensures the completeness of all transactions performed. Checks whether every transaction is completed successfully if not then transaction is aborted at the failure point and the previous transaction is rolled back to its initial state as changes undone
Consistency: Ensures that all changes made through successful transaction are reflected properly on database
Isolation: Ensures that all transactions are performed independently and changes made by one transaction are not reflected on other
Durability: Ensures that the changes made in database with committed transactions persist as it is even after system failure

23) How many Aggregate Functions are available there in SQL?
SQL Aggregate Functions calculates values from multiple columns in a table and returns a single value.
There are 7 aggregate functions we use in SQL
· AVG(): Returns the average value from specified columns
· COUNT(): Returns number of table rows
· MAX(): Returns largest value among the records
· MIN(): Returns smallest value among the records
· SUM(): Returns the sum of specified column values
· FIRST(): Returns the first value
· LAST(): Returns Last value

24) What are Scalar Functions in SQL?
Scalar Functions are used to return a single value based on the input values. Scalar Functions are as follows
· UCASE(): Converts the specified field in upper case
· LCASE(): Converts the specified field in lower case
· MID(): Extracts and returns character from text field
· FORMAT(): Specifies the display format
· LEN(): Specifies the length of text field
· ROUND(): Rounds up the decimal field value to a number

25) What is a trigger?
Database triggers are sets of commands that get executed when an event (Before Insert, After Insert, On Update, On delete of a row) occurs on a table, views.
26) What is Relationship? How many types of Relationship are there?
The relationship can be defined as the connection between more than one tables in the database.
There are 4 types of relationships
· One to One Relationship
· Many to One Relationship
· Many to Many Relationship
· One to Many Relationship

27) What do you mean by Stored Procedures? How do we use it?
A stored procedure is a collection of SQL statements which can be used as a function to access the database. We can create these stored procedures previously before using it and can execute these them wherever we require and also apply some conditional logic to it. Stored procedures are also used to reduce network traffic and improve the performance.
Syntax: CREATE Procedure Procedure_Name
(
//Parameters
)
AS
BEGIN
SQL statements in stored procedures to update/retrieve records
END

28) How we can update the view?
SQL CREATE and REPLACE can be used for updating the view.
Following query syntax is to be executed to update the created view
Syntax: CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition.

29) Explain the working of SQL Privileges?
SQL GRANT and REVOKE commands are used to implement privileges in SQL multiple user environments.  The administrator of the database can grant or revoke privileges to or from users of database object like SELECT, INSERT, UPDATE, DELETE, ALL etc.
GRANT Command: This command is used provide database access to user apart from an administrator.
Syntax: GRANT privilege_name
ON object_name
TO {user_name\PUBLIC\role_name} 
[WITH GRANT OPTION];
In above syntax WITH GRANT OPTIONS indicates that the user can grant the access to another user too.
REVOKE Command: This command is used provide database deny or remove access to database objects.
Syntax: REVOKE privilege_name
ON object_name
FROM {user_name\PUBLIC\role_name;} 

30) What is SQL Injection?
SQL Injection is a type of database attack technique where malicious SQL statements are inserted into an entry field of database such that once it is executed the database is opened for an attacker. This technique is usually used for attacking Data-Driven Applications to have an access to sensitive data and perform administrative tasks on databases.
For Example: SELECT column_name(s) FROM table_name WHERE condition;

31) What is SQL Sandbox in SQL Server?
SQL Sandbox is the safe place in SQL Server Environment where untrusted scripts are executed. There are 3 types of SQL sandbox, such as
· Safe Access Sandbox: Here a user can perform SQL operations such as creating stored procedures, triggers etc. but cannot have access to the memory and cannot create files.
· External Access Sandbox: User can have access to files without having a right to manipulate the memory allocation.
· Unsafe Access Sandbox: This contains untrusted codes where a user can have access to memory.

32) What is the difference between SQL and PL/SQL?
SQL is a structured query language to create and access databases whereas PL/SQL comes with procedural concepts of programming languages.

33) What is the difference between SQL and MySQL?
SQL is a structured query language that is used for manipulating and accessing the relational database, on the other hand, MySQL itself is a relational database that uses SQL as the standard database language.

34) How many row comparison operators are used while working with a subquery?
There are 3-row comparison operators which are used in sub-queries such as IN, ANY and ALL.

35) How to write a query to show the details of a student from Students table whose
name starts with K?
SELECT * FROM Student WHERE Student_Name like ‘%K’;
Here ‘like’ operator is used for pattern matching.

36) What is the difference between Nested Subquery and Correlated Subquery?
Subquery within another subquery is called as Nested Subquery.  If the output of a subquery is depending on column values of the parent query table then the query is called Correlated Subquery.
SELECT adminid(SELEC Firstname+’ ‘+Lastname  FROM Employee WHERE
empid=emp. adminid)AS EmpAdminId FROM Employee
This query gets details of an employee from Employee table.

37) State some properties of Relational databases?
· In relational databases, each column should have a unique name
· Sequence of rows and columns in relational databases are insignificant
· All values are atomic and each row is unique

38) What is Auto Increment?
Auto increment keyword allows the user to create a unique number to be generated when a new record is inserted into the table. AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL SERVER.
Mostly this keyword can be used whenever PRIMARY KEY is used.

39) What do we need to check in Database Testing?
Generally, in Database Testing following thing is need to be tested
· Database Connectivity
· Constraint Check
· Required Application Field and its size
Data Retrieval and Processing With DML operations
· Stored Procedures
· Functional flow

40) What are Indexes in SQL?
The index can be defined as the way to retrieve the data more quickly. We can define indexes using CREATE statements.
Syntax: CREATE INDEX index-name
ON table_name (column_name)
Further, we can also create Unique Index using following syntax;
Syntax: CREATE UNIQUE INDEX index_name
ON table_name (column_name)
******************
UPDATE: Added more questions for your practice.

41) What is the syntax to add a record to a table?
To add a record in a table INSERT syntax is used.
Ex: INSERT into table_name VALUES (value1, value2.);

42) How do you add a column to a table?
To add another column in the table following command has been used.
ALTER TABLE table_name ADD (column_name);

43) Define SQL Delete statement?
Delete is used to delete a row or rows from a table based on the specified condition.
The basic syntax is as follows:
DELETE FROM table_name
WHERE <Condition>

44) What is a stored procedure?
Stored procedure is a set of SQL queries which can take input and send back output.

45) What is identity in SQL?
An identity column in the SQL automatically generates numeric values. We can define a start and increment value of identity column.

46) How to select random rows from a table?
Using SAMPLE clause we can select random rows.
Example:
SELECT * FROM table_name SAMPLE(10);

47) Which TCP/IP port does SQL Server run?
By default SQL Server runs on port 1433.

48) Write a SQL SELECT query that only returns each name only once from a table?
To get the each name only once, we need to use the DISTINCT keyword.
SELECT DISTINCT name FROM table_name;

49) Can we rename a column in the output of SQL query?
Yes using the following syntax we can do this.
SELECT column_name AS new_name FROM table_name;

50) Give the order of SQL SELECT?
Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. Only the SELECT and FROM clause are mandatory.

51) Suppose a Student column has two columns, Name and Marks. How to get name and marks of top three students?
SELECT Name, Marks FROM Student s1 where 3 <= (SELECT COUNT (*) FROM Students s2 WHERE s1.marks = s2.marks).

52) What is SQL Comments?
SQL comments can be put by two consecutive hyphens (–).

53) What do you mean by ROWID?
It’s an 18 character long pseudo column attached with each row of a table.

54) What is a transaction?
A transaction is a sequence of code that runs against a database. It takes the database from one consistent state to another.

55) What is the difference between UNIQUE and PRIMARY KEY constraints?
A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys.
The primary key cannot contain Null values whereas Unique key can contain Null values.

56) What is a composite primary key?
Primary key created on more than one column is called composite primary key.

57) What is an Index?
An Index is a special structure associated with a table speed up the performance of queries. The index can be created on one or more columns of a table.

58) What do you mean by query optimization?
Query optimization is a process in which database system compares different query strategies and selects the query with the least cost.

59) What is Referential Integrity?
Set of rules that restrict the values of one or more columns of the tables based on the values of the primary key or unique key of the referenced table.

60) What is case function?
Case facilitates if-then-else type of logic in SQL. It evaluates a list of conditions and returns one of multiple possible result expressions.

61) Define a temp table?
A temp table is a temporary storage structure to store the data temporarily.

62) Explain the difference between Rename and Alias?
Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column.

63) List the various privileges that a user can grant to another user?
SELECT, CONNECT, RESOURCES.

No comments: