0% found this document useful (0 votes)
12 views70 pages

SQL Question and Answer

Uploaded by

abdelidhankot95
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
12 views70 pages

SQL Question and Answer

Uploaded by

abdelidhankot95
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 70

1) How is data stored physically in SQL Server?

As you know, data in tables is stored in row


and column format at the logical level,
but physically it stores data in data pages
which are allocated from the data files of
the database.
2) Where is the database stored in SQL
Server?
• The system database files for
the database are stored in the users' local
AppData path which is normally hidden. For
example C:\Users\--user--\AppData\Local\
Microsoft\Microsoft SQL Server Local DB\
Instances\LocalDBApp1.
3) what is data and log file in sql
• Data files contain data and objects such as
tables, indexes, stored procedures, and views.
Log files contain the information that is
required to recover all transactions in the
database
4) primary key

• uniquely identifies each row/record


in a database table. A primary key
column cannot have NULL values. A
table can have only one primary key
5) Primary key , foreign key and cluster
index and Non-cluster index
• Primary key , foreign key and cluster index
physical store
• Non-cluster index Logical store
6) View
• Just like simple query and data store in virtual table. It does not
physically exist. It is based on the result set of a SQL statement.
• Since a view is a virtual table – columns of the view cannot be
renamed. To change anything in the view, the view must be
dropped and create again.
• The select statement on the view cannot contain ORDER BY or
INTO TEMP.
• When a table or view is dropped, any views in the same
database are also dropped.
• It is not possible to create an index on a view.
• It is not possible to use DELETE to update a view that is defined
as a join.
7) Can I write insert ,update and delete
statement inside view
• No , it is not possible to write insert ,update and delete
statement inside view
• Using view you can perform this action. Example Create
view table1_View
as
select *
from [dbo].[CustomerAddress]

go

delete
from table1_view
8) Difference between View vs Materialized
View in database
• 1) Views query result is not stored in the disk
or database but Materialized view allow to
store the query result in disk or table
• 2) In case of View we always get latest data
but in case of Materialized view we need to
refresh the view for getting latest data.
• 3) Performance of View is less than
Materialized view
9) can I call view inside another view
• Yes
Indexing view
• Indexing on view used when data not change
frequently. Like reporting
Trigger
• A trigger is a stored procedure in database
which automatically invokes whenever a
special event in the database occurs.
Differences between a Stored Procedure
and a Trigger
• Stored procedures can return values but a trigger
cannot return a value.
• We can execute a stored procedure whenever we
want with the help of the exec command, but a
trigger can only be executed whenever an event
(insert, delete, and update) is fired on the table on
which the trigger is defined.
• We can use transaction statements like begin
transaction, commit transaction, and rollback inside
a stored procedure but we can't use transaction
statements inside a trigger.
What is the maximum number of triggers
can apply to a single table?
• here is no limit. You can create as many as you want.
how many time trigger fired
• It gets fired only ONCE at the end of BULK
UPDATE
• Triggers fire once per statement
sql-query-order-of-operations
User-Defined Data Types?
• User-defined data types can be used when
several tables must store the same type of
data in a column and you must ensure that
these columns have exactly the same data
type, length, and NULLability.
• For example, a user-defined data type called
postal_code could be created based on the
char data type. User-defined data types are
not supported in TABLE variables.
Type of User-Defined Data Types?
• There are six user-defined types:
• Distinct type.
• Structured type
• Reference type
• Array type
• Row type
• Cursor type
Common Table Expressions (CTE)
• CTE is a temporary result set which can be used
within a execution of a SINGLE insert,update,delete
or select query.
• Common Table Expressions (CTE) have two types,
recursive and non-recursive.
• SELECT, INSERT, UPDATE, DELETE, or MERGE
statement.
• more than one CTE in your WITH clause, you must
separate them with commas. CTE can be defined in
functions, stored procedures, triggers or even views.
Advantages of CTE
• CTE improves the code readability.
• CTE provides recursive programming.
• CTE makes code maintainability easier.
• Though it provides similar functionality as a
view, it will not store the definition in
metadata.
CTE not allow following clause
• ORDER BY, unless you also use as TOP
clauseINTOOPTION clause with query hints
FOR BROWSE
What is SQL?
• Structured Query Language is a database tool
which is used to create and access database to
support software application.
What are tables in SQL?

• The table is a collection of record and its


information at a single view.
What are different types of statements
supported by SQL?
• There are 3 types of SQL statements
• 1) DDL (Data Definition Language):Create,
Alter, and Drop
• 2)DML (Data Manipulation Language):Insert,
Update, and Delete.
• 3) DCL (Data Control Language): These
statements are used to set privileges such as
Grant and Revoke database access permission
to the specific user.
How do we use DISTINCT statement? What
is its use?
• DISTINCT statement is used with the SELECT
statement.
• If the records contain duplicate values then
DISTINCT is used to select different values
among duplicate records.
type of temp table
• Local and global temporary
• table Syntax : Local Table '#' and global table
'##'Whilst Temporary
• Tables are created in the tempdb and are
automatically deleted when they are no longer
in use.
• https://www.c-sharpcorner.com/UploadFile/
97fc7a/local-and-global-temporary-tables-in-
sql-server-2008/
Where CTE data is stored
• stored on disk. Function, procedure, view
definitions etc are stored in the database
where they are created.
• CTE can be held in memory
• Indexes cannot be added to a CTE
Can we create temp table in view?
• No, a view consists of a single SELECT
statement. You cannot create or drop tables in
a view.
What are SQL Server functions?
• Function is a database object in Sql Server.
Basically it is a set of sql statements that
accepts only input parameters, perform
actions and return the result. Function can
return only single value or a table.
What does where 1 1 mean in SQL?
• It simply means that the logic is always TRUE.
This is a common trick used in
SQLInjections. ... 1 = 1 is a condition in SQL
that will always be true
What does group by 1 mean in SQL?
• It means to group by the first column
regardless of what it's called. You can do the
same with ORDER BY
Where are table variables stored in SQL
Server?
• table variables are in memory objects
• Table variable can have a maximum of 128
characters and a Temp Table can have 116
characters.
handle two parallel update request in sql
with transaction
• If two transactions try to update the same
row, the second transaction must wait for the
first one to either commit or rollback and if
the first transaction has been committed, then
the second transaction DML WHERE clause
must be reevaluated to see if the match is still
relevant.
How can you create an empty table from
an existing table?
• Select * into studentcopy from student where
1=2 -- Copy only structure
• select * into countryCopy3 from Country
where 1=1 - COpy structure and data
What is intersect ?
• his means INTERSECT returns only common
rows returned by the two SELECT statements.
• Syntax - Select studentID from student.
<strong>INTERSECT </strong> Select
StudentID from Exam
• MySQL does not support the INTERSECT
operator.
Inner Join
• Inner join return only matching data in both
table. Not return data which is not match in
one of table
left join
• Return all data from left table and match data
from second table , no return second table
data which is not match in first table
Right join
• Return all data from right table and match
data from second table, not match data
display value null.
full outer join
• Combination of left ,right and inner join.
• https://www.youtube.com/watch?v=KTvYHEnt
vn8
What is truncate in sql ?
• Truncate remove all the data in table in one
shot and reset identity value and starting from
top.
• You cannot apply filter on truncate table .
• truncate cannot return no of rows affected
count.
• After truncate table you cannot roll back.
• Syntax : Truncate table <TableName>
What is cross apply?
• Table and table value function join not work . Need to
implement cross join to get data.
• Cross apply same as inner join .
• create function [dbo].[getAddress](@CountyID int)
• returns table
• As
• return (select * from CustomerAddress where CountryId =
@CountyID)
• Go
• select c.* from Country c cross apply [dbo].[getAddress]
(c.CountryId)
what is Outer apply?
• Nothing but same as outer join. Table and
table value function join not work
What is Rank function in sql server ?
• For example : highest salary employe rnak 1 and lowst
salary employe rank last.
• Select EmpId,DepId,Salary,Name RANK()Over(order by
salary desc) as 'Rank' from employee
• Department wise Rank : Select
EmpId,DepId,Salary,Name RANK()Over(Partition by
DepID order by salary desc) as 'Rank' from employee
• IN Rank both department same salary that may be
result not correct you may need to some other option
Is there any function which generates
Rank(similar) in sql server?
• Same as RANK function just syntax Change
Dense_RANK()
• https://www.youtube.com/watch?v=92OSTvW
0Ge8
Count record in sql
• Null record cannot count in sql Example :
select count(empname) from employee
• Count(*) return count all data
ROW_Number,Rank,Dense_RANK, Partition
BY
• Row_Number : Generate Unique number and
partition by generate group wise unique number.
Example : 1,2,3,4,5 and Partition by : 1,2,3,4,1,2,3
• Rank : Rank generate unique number only when
unique value other wise not generate unique
number , some unique number missing in
duplicate value . Example : 1,1,3,4,5,5,6
• Dense_RANK : Dense rank generate unique
number based on value . Example : 1,1,2,3,4,5,6,6
Difference between TRUNCATE , DELETE
and DROP in SQL Server
• TRUNCATE
• TRUNCATE is a DDL command
• TRUNCATE is executed using a table lock and whole table is locked for remove all records.
• We cannot use Where clause with TRUNCATE.
• TRUNCATE removes all rows from a table.
• Minimal logging in transaction log, so it is performance wise faster.
• TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.
• Identify column is reset to its seed value if table contains any identity column.
• To use Truncate on a table you need at least ALTER permission on the table.
• Truncate uses the less transaction space than Delete statement.
• Truncate cannot be used with indexed views.
• DELETE
DELETE is a DML command.
• DELETE is executed using a row lock, each row in the table is locked for deletion.
• We can use where clause with DELETE to filter & delete specific records.
• The DELETE command is used to remove rows from a table based on WHERE condition.
• It maintain the log, so it slower than TRUNCATE.
• The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row.
• Identity of column keep DELETE retain the identity.
• To use Delete you need DELETE permission on the table.
• Delete uses the more transaction space than Truncate statement.
• Delete can be used with indexed views.
• DROP
The DROP command removes a table from the database.
• All the tables' rows, indexes and privileges will also be removed.
• No DML triggers will be fired.
• The operation cannot be rolled back.
• DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command.
• DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.
what is difference between varchar and
nvarchar
• Nvarchar stores UNICODE data
• Varchar stores ASCII data Regarding memory
usage
• Nvarchar uses 2 bytes per character
• varchar uses 1 bytes per character
Should I use varchar or Nvarchar?
• If you have requirements to store UNICODE or
multilingual data, nvarchar is the
choice. Varchar stores ASCII data
and should be your data type of choice for
normal use
• https://www.guru99.com/sql-interview-questi
ons-answers.html

• https://www.softwaretestinghelp.com/50-
popular-sql-interview-questions-for-testers/
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.
What is a composite primary key?
• Primary key created on more than one column
is called composite primary key.
• Which TCP/IP port does SQL Server run?
• By default SQL Server runs on port 1433.
• How to select random rows from a table?
• SELECT top 1 * FROM student ORDER BY
NEWID()
What is Relationship? How many types of
Relationship are there?
• There are 4 types of relationships
• One to One Relationship
• Many to One Relationship
• Many to Many Relationship
• One to Many Relationship
What is the Cartesian product of table?
• output of Cross Join is called as a Cartesian
product.
• For Example, if we join two tables having 15
and 20 columns the Cartesian product of two
tables will be 15×20=300 Rows.
What is the use of NVL function?
• NVL function is used to convert the null value
to its actual value.
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
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
What are transaction and its controls?
• 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
What are the properties of a transaction?

• Generally, these properties are referred as


ACID properties. They are:
• Atomicity
• Consistency
• Isolation
• Durability.
How to fetch alternate records from a
table?
• Records can be fetched for both Odd and Even row numbers -.
• To display even numbers-.
• select * from(
• Select ROW_NUMBER() OVER(ORDER BY studentId asc) AS
'RowNumber',studentId, studentName from student
• ) as t where (t.RowNumber %2) =1

• To display odd numbers-.


• select * from(
• Select ROW_NUMBER() OVER(ORDER BY studentId asc) AS
'RowNumber',studentId, studentName from student
• ) as t where (t.RowNumber %2) =0

• No result found if we increase value 2,3,4


How to fetch common records from two
tables?
• Select studentID from student.
<strong>INTERSECT </strong>
• Select StudentID from Exam
What is Union, minus and Interact
commands?
• UNION operator is used to combine the results of
two tables, and it eliminates duplicate rows from
the tables.
• MINUS operator is used to return rows from the
first query but not from the second query.
Matching records of first and second query and
other rows from the first query will be displayed as
a result set.
• INTERSECT operator is used to return matching
rows by both the queries.
What is recursive stored procedure?
• Store procedure (like [dbo].[test]) inside call
again same store procedure (like [dbo].[test])
is called recursive stored procedure.
• maximum nesting level of 32.
• expand a tree relationship.
Advantages and Disadvantages of Stored
Procedure?
• Stored procedure can be used as a modular
programming – means create once, store and
call for several times whenever required. This
supports faster execution instead of executing
multiple queries. This reduces network traffic
and provides better security to the data.
• Disadvantage is that it can be executed only in
the Database and utilizes more memory in the
database server.
What is collation?
• Collation is defined as set of rules that determine
how character data can be sorted and compared.
• What are all different types of collation
sensitivity?
• Case Sensitivity – A and a and B and b.
• Accent Sensitivity.
• Kana Sensitivity – Japanese Kana characters.
• Width Sensitivity – Single byte character and
double byte character.
What is a constraint?
• Constraint can be used to specify the limit on
the data type of table.
• NOT NULL.
• CHECK.
• DEFAULT.
• UNIQUE.
• PRIMARY KEY.
• FOREIGN KEY.
Which operator is used in query for
pattern matching?
• LIKE operator is used for pattern matching,
and it can be used as -.
• % - Matches zero or more characters.
• _(Underscore) – Matching exactly one
character.
What is the command used to fetch first 5
characters of the string?
• Select SUBSTRING(StudentName,1,5) as
studentname from studentSelect
• RIGHT(Studentname,5) as studentname from
student
How does index actually makes search
faster
• Creating B-Tree Structure and balance tree
• If indexes not apply then sql search sequentially and
this type of scan is Table Scan
• Data divided in three part root node, non-leaf nodes,
Leaf node.
• Record search by b –tree structure called index seek
and scan.
• In high transaction like multiple insert , update delete
indexes slow down performance.
• https://www.youtube.com/watch?v=rtmeNwn4mEg
Sub query and co related sub query
• Sub query nothing but query inside another query.
• In Sub query first inner query execute after outer query execute.
• Outer query reference used in inner query is called co-related
query.
• In correlated query outer query pass data to inner query after
pass gain to outer query.
• In sub query no reference between inner query and outer
query ,so inner query completely independent.
• Sub query execute faster than co related query because sub
query execute one time but corelated query execute one by
one .
• https://www.youtube.com/watch?v=00Vxnod-6iE
Difference between stored procedure and
function in sql server
• https://www.youtube.com/watch?
v=LjojQC1gZBI

You might also like