Most Repeated SQL Interview Questions For You Guys !!
Most Repeated SQL Interview Questions For You Guys !!
Although SQL is an ANSI (American National Standards Institute) standard, there are
different versions of the SQL language.
However, to be compliant with the ANSI standard, they all support at least the major
commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.
Note: Most of the SQL database programs also have their own proprietary extensions in
addition to the SQL standard!
SQL stands for Structured Query Language. SQL lets you access and manipulate
databases. SQL is an ANSI (American National Standards Institute) standard.
3. SQL is (referring to it as a Programming Language)
5. What is MySQL?
MySQL is the most popular Open Source SQL database management system developed,
distributed, and supported by Oracle Corporation.
“What is the difference between SQL and MySQL?” or 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.
6. What are some properties of PL/SQL?
Another common SQL interview question regarding PL/SQL may come in a different
form:
“What is the difference between SQL and PL/SQL? or Difference between SQL and PL/SQL:
SQL is a Structured Query Language used to issue a single query or execute a single
insert/update/delete.
• SQL may be considered as the source of data for our reports, web pages and
screens.
• SQL is a data oriented language used to select and manipulate sets of data.
MySQL uses TINYINT (1) data type to represent Boolean values. A value of zero is
considered false. Non-zero values are considered true.
8. What data type would you choose if you wanted to store the distance (rounded
to the nearest mile)?
--Select all:
SELECT * FROM Customers;
A SELECT statement retrieves zero or more rows from one or more database tables or
database views.
As SQL is a declarative programming language, SELECT queries specify a result set, but
do not specify how to calculate it.
14. With SQL, how do you select a column named “FirstName” from a table named
“Customers”?
SELECT Syntax
Here, column1, column2, … are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use the following syntax:
The SQL FROM clause is used to list the tables and any joins required for the SQL
statement.
Inside a table, a column often contains many duplicate values; and sometimes you only
want to list the different (distinct) values.
17. Consider the following schema ADDRESSES (id, street_name, number, city,
state) Which of the following query would display the distinct cities in the
ADDRESSES table?
18. With SQL, how do you select all the records from a table named “Customers”
where the value of the column “FirstName” is “John”?
The WHERE clause is used to extract only those records that fulfill a specified condition.
SQL requires single quotes around text values (most database systems will also allow
double quotes).
19. The OR operator displays a record if ANY conditions listed are true. The AND
operator displays a record if ALL of the conditions listed are true.
The WHERE clause can be combined with AND , OR , and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND are TRUE .
The OR operator displays a record if any of the conditions separated by OR are TRUE .
AND Syntax
OR Syntax
NOT Syntax
• ’=’ Equal to
21. With SQL, how do you select all the records from a table named “Customers”
where the “FirstName” is “John” and the “LastName” is “Jackson”?
You must use the AND operator that displays a record if all the conditions separated by
AND are TRUE and the = (‘equal’) comparison operator.
The easiest way to generate random rows in MySQL is to use the ORDER BY RAND()
clause.
SELECT * FROM tbl ORDER BY RAND() LIMIT 10;
This can work fine for small tables. However, for big table, it will have a serious
performance problem as in order to generate the list of random rows, MySQL need to
assign random number to each row and then sort them.
Even if you want only 10 random rows from a set of 100k rows, MySQL need to sort all
the 100k rows and then, extract only 10 of them.
23. Examine the following code. What will the value of price be if the statement
finds a NULL value? SELECT name, ISNULL(price, 50) FROM PRODUCTS
Note: It is very important to understand that a NULL value is different from a zero value
or a field that contains spaces. A field with a NULL value is one that has been left blank
during record creation!
MySQL
The MySQL IFNULL() function lets you return an alternative value if an expression is
NULL:
SQL Server
The SQL Server ISNULL() function lets you return an alternative value when an
expression is NULL :
The MS Access IsNull() function returns TRUE (-1) if the expression is a null value,
otherwise FALSE (0) :
Oracle
24. Which operator is used to search for a specified text pattern in a column?
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
There are two wildcards used in conjunction with the LIKE operator:
Examples:
• WHERE CustomerName LIKE ‘a%’ – Finds any values that starts with “a”
• WHERE CustomerName LIKE ‘%a’ – Finds any values that ends with “a”
• WHERE CustomerName LIKE ‘%or%’ – Finds any values that have “or” in any
position
• WHERE CustomerName LIKE ‘_r%’ – Finds any values that have “r” in the second
position
• WHERE CustomerName LIKE ‘a_%_%’ – Finds any values that starts with “a” and
are at least 3 characters in length
• WHERE ContactName LIKE ‘a%o’ – Finds any values that starts with “a” and ends
with “o”
25. How to write a query to show the details of a student from Students table
whose FirstName starts with ‘K’?
The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
28. With SQL, how do you select all the records from a table named “Customers”
where the “LastName” is alphabetically between (and including) “Brooks” and
“Gray”?
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT); --subquery
31. What function to use to round a number to the smallest integer value that is
greater than or equal to a number?
The CEILING() function returns the smallest integer value that is greater than or equal to
the specified number.
The CEIL() function is a synonym for the CEILING() function and also returns the smallest
integer value that is greater than or equal to a number.
Example:
The CURDATE() function returns the current date. This function returns the current date
as a YYYY-MM-DD format if used in a string context, and as a YYYYMMDD format if
used in a numeric context.
The MAX() function returns the largest value of the selected column.
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
The COUNT() function returns the number of rows that matches a specified criteria.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
• MIN and MAX return the lowest and highest values in a particular column,
respectively.
36. With SQL, how can you return the number of records in the “Customers” table?
37. Which 2 SQL keywords specify the sorting direction of the result set retrieved
with ORDER BY clause?
**ASC DESC**
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
ORDER BY Syntax
38. If you don’t specify ASC or DESC for an ORDER BY clause, the following is used
by default:
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
39. Suppose a Students table has two columns, name and mark. How to get name
and mark of top three students?
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of records. Returning a
large number of records can impact on performance.
Not all database systems support the SELECT TOP clause.MySQL supports the LIMIT
clause to select a limited number of records, while Oracle uses ROWNUM .
40. With SQL, how can you return all the records from a table named “Customers”
sorted descending by “FirstName”?
SQL aggregate functions like COUNT , AVG , and SUM have something in common: they
all aggregate across the entire table. But what if you want to aggregate only part of a
table? For example, you might want to count the customers having the same name. In
situations like this, you’d need to use the GROUP BY clause. GROUP BY allows you to
separate data into groups, which can be aggregated independently of one another.
42. What is the difference between HAVING clause and WHERE clause?
Both specify a search condition but HAVING clause is used only with the SELECT
statement and typically used with GROUP BY clause.
If GROUP BY clause is not used then HAVING behaves like WHERE clause only.
• Only the groups that meet the HAVING criteria will be returned.
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
The most common type of join used in day to day queries is INNER JOIN .
The INNER JOIN keyword selects records that have matching values in both tables.
The LEFT JOIN keyword returns all records from the left table (table1), and the matched
records from the right table (table2). The result is NULL from the right side, if there is no
match.
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matched records from the left table (table1). The result is NULL from the left side, when
there is no match.
The FULL OUTER JOIN keyword return all records when there is a match in either left
(table1) or right (table2) table records.
Note: FULL OUTER JOIN can potentially return very large result-sets!
SQL Self JOIN
A self JOIN is a regular join, but the table is joined with itself.
The SQL CROSS JOIN produces a result set which is the number of rows in the first table
multiplied by the number of rows in the second table if no WHERE clause is used along
with CROSS JOIN .This kind of result is called as Cartesian Product.
If WHERE clause is used with CROSS JOIN , it functions like an INNER JOIN .
Displays rows (records) only when the values of the Key in table A and the foreign
key in table B are equal.
The INNER JOIN keyword selects records that have matching values in both tables.
For example, for a Faculty table the lookup tables might be Division, with DivisionID as
the PK, Country, with CountryID as the PK, and Nationality, with NationalityID as the PK.
To join Faculty to the Division, Country, and Nationality tables, the fields DivisionID,
CountryID and NationalityID would need to be foreign keys in the Faculty table.
The SQL CROSS JOIN produces a result set which is the number of rows in the first table
multiplied by the number of rows in the second table if no WHERE clause is used along
with CROSS JOIN .This kind of result is called as Cartesian Product.
If WHERE clause is used with CROSS JOIN , it functions like an INNER JOIN .
SELECT *
FROM table1
CROSS JOIN table2;
51. In relational algebra the INTERSECTION of two sets (set A and Set B)
corresponds to
A AND B
The SQL INTERSECT clause/operator is used to combine two SELECT statements, but
returns rows only from the first SELECT statement that are identical to a row in the
second SELECT statement. This means INTERSECT returns only common rows returned
by the two SELECT statements.
INTERSECT Syntax
52. In relational algebra the UNION of two sets (set A and Set B) corresponds to
A OR B
The SQL UNION clause/operator is used to combine the results of two or more SELECT
statements without returning any duplicate rows.
Union Syntax
UNION ALL – returns all rows selected by either query, including all duplicates.
54. Having a list of Customer Names that searched for product ‘X’ and a list of
customer Names that bought the product ‘X’. What set operator would you use to
get only those who are interested but did not bought product ‘X’ yet?
MINUS
The SQL MINUS operator is used to return all rows in the first SELECT statement that are
not returned by the second SELECT statement. Each SELECT statement will define a
dataset. The MINUS operator will retrieve all records from the first dataset and then
remove from the results all records from the second dataset.
MINUS Syntax
Subquery.
A SELECT clause
A FROM clause
A WHERE clause
A subquery is usually added within the WHERE clause of another SQL SELECT statement.
You can use the comparison operators, such as > , < , or = . The comparison operator
can also be a multiple-row operator, such as IN , ANY , or ALL .
A subquery is also called an inner query or inner select, while the statement containing a
subquery is also called an outer query or outer select.
The inner query executes first before its parent query so that the results of an inner
query can be passed to the outer query.
The subquery can be nested inside a SELECT , INSERT , UPDATE , or DELETE statement or
inside another subquery.
You can use the comparison operators, such as > , < , or = . The comparison operator
can also be a multiple-row operator, such as IN , ANY , or ALL .
59. A subquery that uses a correlation name from the outer query is called a
If the output of a subquery is depending on column values of the parent query table
then the query is called Correlated Subquery.
CASE Syntax
CASE expression
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
WHEN conditionN THEN resultN
ELSE result
END
DDL (Data Definition Language): It is used to define the database structure such as
tables. It includes three statements such as Create, Alter, and Drop.
DML (Data Manipulation Language): These statements are used to manipulate the data
in records. Commonly used DML statements are Select, Insert, Update, and Delete.
Note: Some people prefer to assign the SELECT statement to a category of its own
called: DQL. Data Query Language.
DCL (Data Control Language): These statements are used to set privileges such as Grant
and Revoke database access permission to the specific user.
• ALTER Statements
• CREATE Statements
• DROP Statements
• TRUNCATE TABLE
SELECT
INSERT
UPDATE
DELETE
64. Grant and Revoke commands are under
GRANT : Used to provide any user access privileges or other privileges for the database.
67. When inserting data in a table do you have to specify the list of columns you
are inserting values for?
The first way specifies both the column names and the values to be inserted:
If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query. However, make sure the order of the values is in the
same order as the columns in the table. The INSERT INTO syntax would be as follows:
68. With SQL, how can you insert a new record into the “Customers” table?
69. With SQL, how can you insert “Hawkins” as the “LastName” in the “Customers”
table?
To create a temporary table, you just need to add the TEMPORARY keyword to the
CREATE TABLE statement.
Example:
UPDATE Syntax
- UPDATE table_name
- SET column1 = value1, column2 = value2, ...
- WHERE condition;
72. What is the keyword is used in an UPDATE query to modify the existing value?
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
73. How can you change “Jackson” into “Hawkins” in the “LastName” column in
the Customer table?
DELETE Syntax
DELETE Syntax
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
INSERT Syntax
SELECT Syntax
The basic difference in both is DELETE is DML command and TRUNCATE is DDL.
DELETE is used to delete a specific row from the table whereas TRUNCATE is used to
remove all rows from the table
We can use DELETE with WHERE clause but cannot use TRUNCATE with it.
Syntax
A collation is a set of rules that defines how to compare and sort character strings.
Detailed Explanation:
A character set is a set of symbols and encodings. A collation is a set of rules for
comparing characters in a character set. Let’s make the distinction clear with an example
of an imaginary character set.
Suppose that we have an alphabet with four letters: A, B, a, b. We give each letter a
number: A = 0, B = 1, a = 2, b = 3. The letter A is a symbol, the number 0 is the
encoding for A, and the combination of all four letters and their encodings is a character
set.
Suppose that we want to compare two string values, A and B. The simplest way to do
this is to look at the encodings: 0 for A and 1 for B. Because 0 is less than 1, we say A is
less than B. What we’ve just done is apply a collation to our character set. The collation
is a set of rules (only one rule in this case): “compare the encodings.” We call this
simplest of all possible collations a binary collation.
But what if we want to say that the lowercase and uppercase letters are equivalent?
Then we would have at least two rules: (1) treat the lowercase letters a and b as
equivalent to A and B; (2) then compare the encodings. We call this a case-insensitive
collation. It is a little more complex than a binary collation.
In real life, most character sets have many characters: not just A and B but whole
alphabets, sometimes multiple alphabets or eastern writing systems with thousands of
characters, along with many special symbols and punctuation marks. Also in real life,
most collations have many rules, not just for whether to distinguish lettercase, but also
for whether to distinguish accents (an “accent” is a mark attached to a character as in
German Ö), and for multiple-character mappings (such as the rule that Ö = OE in one of
the two German collations).
Source: dev.mysql.com
The following SQL statement defines the “ID” column to be an auto-increment primary
key field in the “Persons” table:
The following SQL statement defines the “ID” column to be an auto-increment primary
key field in the “Persons” table:
You will have to create an auto-increment field with the sequence object (this object
generates a number sequence).
The code above creates a sequence object called seq_person, that starts with 1 and will
increment by 1. It will also cache up to 10 values for performance. The cache option
specifies how many sequence values will be stored in memory for faster access.
To insert a new record into the “Persons” table, we will have to use the nextval function
(this function retrieves the next value from seq_person sequence):
The SQL statement above would insert a new record into the “Persons” table. The “ID”
column would be assigned the next number from the seq_person sequence. The
“FirstName” column would be set to “Lars” and the “LastName” column would be set to
“Monsen”.
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
• INDEX - Used to create and retrieve data from the database very quickly
83. The NOT NULL constraint enforces a column to not accept null values.
The UNIQUE constraint ensures that all values in a column are different.
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this
column.
If you define a CHECK constraint on a table it can limit the values in certain columns
based on values in other columns in the row.
The following SQL creates a CHECK constraint on the “Age” column when the “Persons”
table is created. The CHECK constraint ensures that you can not have any person below
18 years:
MySQL:
86. What is the difference between UNIQUE and PRIMARY KEY constraints?
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for
a column or set of columns.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
Syntax
TRUNCATE removes all rows from the table which cannot be retrieved back, DROP
removes the entire table from the database and it cannot be retrieved back.
The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
You rename a column using the ALTER TABLE and CHANGE commands together to
change an existing column.
Syntax
91. Consider the following schema ADDRESSES (id, street_name, number, city,
state) Which code snippet will alter the table ADDRESSES and delete the column
named CITY?
To delete a column in a table, use the following syntax (notice that some database
systems don’t allow deleting a column):
Indexes are used to retrieve data from the database very fast. The users cannot see the
indexes, they are just used to speed up searches/queries.
Note: Updating a table with indexes takes more time than updating a table without
(because the indexes also need an update). So, only create indexes on columns that will
be frequently searched against.
One table can have only one clustered index but multiple nonclustered indexes.
Clustered indexes store data physically in the table or view and non-clustered indexes
do not store data in table as it has separate structure from data row.
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}
System Privilege: System privileges deal with an object of a particular type and
specifies the right to perform one or more actions on it which include Admin allows a
user to perform administrative tasks, ALTER ANY INDEX, ALTER ANY CACHE GROUP
CREATE/ALTER/DELETE TABLE, CREATE/ALTER/DELETE VIEW etc.
Object Privilege: This allows to perform actions on an object or object of another
user(s) viz. table, view, indexes etc. Some of the object privileges are EXECUTE, INSERT,
UPDATE, DELETE, SELECT, FLUSH, LOAD, INDEX, REFERENCES etc.
96. List the various privileges that a user can grant to another user?
Locking is a process preventing users from reading data being changed by other users,
and prevents concurrent users from changing the same data at the same time.
COMMIT command is used to permanently save any transaction into the database.
When we use any DML command like INSERT , UPDATE or DELETE , the changes made
by these commands are not permanent, until the current session is closed, the changes
made by these commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
COMMIT;
ROLLBACK command
This command restores the database to last committed state. It is also used with
SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and
realise that those changes were not required, then we can use the ROLLBACK command
to rollback those changes, if they were not committed using the COMMIT command.
• ROLLBACK TO savepoint_name;
• SAVEPOINT command
• SAVEPOINT savepoint_name;
In short, using this command we can name the different states of our data in any table
and then rollback to that state using the ROLLBACK command whenever required.
Committed.
It does nothing. Once a transaction has executed commit, its effects can no longer be
undone by rollback.
The characteristics of these four properties as defined by Reuter and Härder are as
follows:
Atomicity
Atomicity requires that each transaction be “all or nothing”: if one part of the
transaction fails, then the entire transaction fails, and the database state is left
unchanged. An atomic system must guarantee atomicity in each and every situation,
including power failures, errors and crashes. To the outside world, a committed
transaction appears (by its effects on the database) to be indivisible (“atomic”), and an
aborted transaction does not happen.
Consistency
The consistency property ensures that any transaction will bring the database from one
valid state to another. Any data written to the database must be valid according to all
defined rules, including constraints, cascades, triggers, and any combination thereof.
This does not guarantee correctness of the transaction in all ways the application
programmer might have wanted (that is the responsibility of application-level code), but
merely that any programming errors cannot result in the violation of any defined rules.
Isolation
The isolation property ensures that the concurrent execution of transactions results in a
system state that would be obtained if transactions were executed sequentially, i.e., one
after the other. Providing isolation is the main goal of concurrency control. Depending
on the concurrency control method (i.e., if it uses strict - as opposed to relaxed -
serializability), the effects of an incomplete transaction might not even be visible to
another transaction.
Durability
The durability property ensures that once a transaction has been committed, it will
remain so, even in the event of power loss, crashes, or errors. In a relational database,
for instance, once a group of SQL statements execute, the results need to be stored
permanently (even if the database crashes immediately thereafter). To defend against
power loss, transactions (or their effects) must be recorded in a non-volatile memory.
If autocommit mode is enabled, each SQL statement forms a single transaction on its
own. By default, most of DBMS start the session for each new connection with
autocommit enabled, so they do a commit after each SQL statement if that statement
did not return an error. If a statement returns an error, the commit or rollback behavior
depends on the error.
REPEATABLE READ
TRUE
A view.
A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.
You can add SQL functions, WHERE , and JOIN statements to a view and present the
data as if the data were coming from one single table.
The SQL UPDATE VIEW command can be used to modify the data of a view.
All views are not updatable. So, UPDATE command is not applicable to all views. An
updatable view is one which allows performing a UPDATE command on itself without
affecting any other table.
2. The view must include the PRIMARY KEY of the table based upon which the view
has been created.
3. The view should not have any field made out of aggregate functions.
4. The view must not have any DISTINCT clause in its definition.
5. The view must not have any GROUP BY or HAVING clause in its definition.
7. If the view you want to update is based upon another view, the later should be
updatable.
8. Any of the selected output fields (of the view) must not use constants, strings or
value expressions.
Simplify queries: You can use database view to hide the complexity of underlying tables
to the end-users and external applications
All changes performed by SQL statements are executed only after a COMMIT command.
A database view helps limit data access to specific users. You may not want a subset of
sensitive data can be queryable by all users
The answer depends on the type of view. In case of normal view, the answer is NO it
only contains query based on a base table but in case of materialized view, YES it does
contain data and for the updated data in the base table, it needs to be refreshed.
111. Inside a stored procedure you to iterate over a set of rows returned by a
query using a
• Declare Cursor
• Open Cursor
• Retrieve row from the Cursor
• Process the row
• Close Cursor
• Deallocate Cursor
112. How do you call the process of finding a good strategy for processing a
query?
Triggers are, in fact, written to be executed in response to any of the following events:
Action and Event are two main components of SQL triggers when certain actions are
performed the event occurs in response to that action.
Syntax
Trigger.
• SQL injection is a code injection technique that might destroy your database.
• SQL injection is the placement of malicious code in SQL statements, via web page
input.
1) What is the difference between inner and outer join? Explain with example.
- Inner join returns rows when there is at least one match in both tables
- Outer join will return matching rows from both tables as well as any unmatched rows from one
or both the tables
2) What is the difference between JOIN and UNION?
- SQL JOIN allows us to “lookup” records on other table based on the given conditions between
two tables.
- UNION operation allows us to add 2 similar data sets to create resulting data set that contains
all the data from the source data sets. Union does not require any condition for joining.
- UNION operation returns only the unique records from the resulting data set
- UNION ALL will return all the rows, even if one or more rows are duplicated to each other.
- UNION combines the results from 2 tables and eliminates duplicate records from the result set.
- MINUS operator when used between 2 tables, gives us all the rows from the first table except
the rows which are present in the second table.
- INTERSECT operator returns us only the matching or common rows between 2 result sets.
6) How can we transpose a table using SQL (changing rows to column or vice-versa) ?
- SELECT name, sal, (SELECT COUNT(*) FROM EMPLOYEE i WHERE o.name >= i.name) row_num
FROM EMPLOYEE o
order by row_num
WHERE (SELECT count(*) FROM EMPLOYEE i WHERE i.name < o.name) < 5
Dynamic Management Views (DMVs), are functions that give you information on the state of the
server. DMVs, for the most part, are used to monitor the health of a server. They really just give you a
snapshot of what’s going on inside the server. They let you monitor the health of a server instance,
troubleshoot major problems and tune the server to increase performance
In a nutshell, a temp table is a temporary storage structure. What does that mean? Basically,
you can use a temp table to store data temporarily so you can manipulate and change it before it
reaches its destination format.
11) What’s the difference between a local temp table and a global temp table?
Local tables are accessible to a current user connected to the server. These tables disappear
once the user has disconnected from the server. Global temp tables, on the other hand, are available to
all users regardless of the connection. These tables stay active until all the global connections are closed.
Delete command removes the rows from a table based on the condition that we provide with a
WHERE clause.
Truncate will actually remove all the rows from a table and there will be no data in the table
after we run the truncate command.
A view is simply a virtual table that is made up of elements of multiple physical or “real” tables.
Views are most commonly used to join multiple tables together, or control access to any tables existing
in background server processes.
Basically, when SQL Server is enabled the server instant listens to the TCP port 1433. It can
be changed from the Network Utility TCP/IP properties.
15) What are the difference between clustered and a non-clustered index?
A clustered index is a special type of index that reorders the way records in the table are
physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index
contain the data pages.
A non clustered index is a special type of index in which the logical order of the index does not
match the physical stored order of the rows on disk. The leaf node of a non clustered index does not
consist of the data pages. Instead, the leaf nodes contain index rows.
A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table
should have a primary key constraint to uniquely identify each row and only one primary key constraint
can be created for each table. The primary key constraints are used to enforce entity integrity.
A FOREIGN KEY constraint prevents any actions that would destroy links between tables with
the corresponding data values. A foreign key in one table points to a primary key in another table.
Foreign keys prevent actions that would leave rows with foreign key values when there are no primary
keys with that value. The foreign key constraints are used to enforce referential integrity.
16) What's the difference between a primary key and a unique key?
Both primary key and unique key enforces uniqueness of the column on which they are defined.
But by default primary key creates a clustered index on the column, where are unique creates a
non-clustered index by default.
Another major difference is that, primary key doesn't allow NULLs, but unique key allows one
NULL only.
Stored procedure can reduced network traffic and latency, boosting application performance.
Stored procedure execution plans can be reused, staying cached in SQL Server's memory,
reducing server overhead.
Stored procedures can encapsulate logic. You can change stored procedure code without
affecting clients.