SQL Questions
SQL Questions
3. Hassan said,
In question 10, it is worth mentioning that a table can have no more than 249 non
clustered indexes - as opposed to saying “as many as we can on the db”
4. Upendra said,
Hi,
Can you tell me how to get a query text in MS SQL SErver ?
If we want the same in Oracle we can get it by executing :
select SQL_TEXT from V$SQL
Thanks !!
6. Jason said,
Hello,
I have an issue where we have a temp table (I’ll just call it #temp for this
question) where we store table info that we are creating through an app….then
once it’s changed we need to copy all of the data from that table into a global
temp table…say we’ll call this one ##global…
can anyone tell me a way to copy or insert all of the columns and data from #temp
into ##global please? and withought having to include all the existing colum
names in the #Temp tabe in the script. Is it even possible withough using a bcp to
out it then another to in it from files?
Thank you,
Jason
7. mEmENT0m0RI said,
8. vinay said,
can u tell the command to get all table names from a database
9. Himadrish said,
Hello Jason ,
I think we can shoot any triger to do the job. Any app when work on #tmp table
will fire the triger in the sql server, which will do the job to transfer the data from
#tmp to #global.
Cheers!
Himadrish
10.Chandraprakash said,
Hi Vinay,
To get all the table names from a database just execute “sp_tables” system store
procedure without the quotes.
Regards,
Chandraprakash.
Hello vinay,
12.manmeet said,
13.sangeetha said,
Hi ,
Thanks a lot.It’s really helpfull.
14.sangeetha said,
What is a Function?
Set of statements to perform a particular task.It compute a value and returns it.
if u call 1000 times a function,it has the same effect.It cannot be executed
individually.
when u call a function,u must assign a value to the variable.
Note:Returns a single value.
Question: Which one is newer and better to use MS SQL server 2000 or SQL
server 7.0?
Thanks
Rod
16.Vidhya said,
Answer to question 15 is SQL Server 2000 is newer and better than SQL 7.0
Q: How to update one according to other table if one column is identical in both?
19.vinay said,
20.Joji said,
42.
sp_addlogin ‘Buck’, ‘password’With the name Buck and a password
If you have Windows authentication set on your server, you use a different
command, and you don’t have to specify the password:
sp_grantlogin ‘HQ\Buck’
or we can say
GRANT SELECT, UPDATE
ON authors
TO [HQ\Buck
REVOKE SELECT
ON authors
FROM [HQ\Buck]
DENY INSERT
ON authors
TO [HQ\Buck]
46.
Three command to get version or operating system related infomation.
Select @@Version
Or
EXEC sp_MSgetversion
or
Exec xp_msver
42.
Grant, Revoke, Deny
or
To create SQL Server logins using SQL authentication is sp_addlogin. The format
looks like this:
If you have Windows authentication set on your server, you use a different
command, and you don’t have to specify the password:
sp_grantlogin ‘HQ\Buck’
46.
Three command to get version or operating system related infomation.
Select @@Version
Or
EXEC sp_MSgetversion
or
Exec xp_msver
42.
Grant, Revoke, Deny
or
To create SQL Server logins using SQL authentication is sp_addlogin. The format
looks like this:
If you have Windows authentication set on your server, you use a different
command, and you don’t have to specify the password:
sp_grantlogin ‘HQ\Buck’
46.
Three command to get version or operating system related infomation.
Select @@Version
Or
EXEC sp_MSgetversion
or
Exec xp_msver
52.
SELECT STUFF(’wabbit_season’, 7, 1, ‘_hunting_’)
Result will be
Microsoft SQL Server [returns ‘wabbit_hunting_season’]
Microsoft SQL Server uses the STUFF function to overwrite existing characters.
Using this syntax, STUFF(string_expression, start, length,
replacement_characters), string_expression is the string that will have characters
substituted, start is the starting position, length is the number of characters in the
string that are substituted, and replacement_characters are the new characters
interjected into the string.
————————————-
This example replaces the string cde in abcdefghi with xxx.
SELECT REPLACE(’abcdefghicde’,'cde’,'xxx’)
GO
————
abxxxfghixxx
(1 row(s) affected)
53.
when Quoted identifiers is ON
Quoted identifiers are delimited by double quotation marks (”):
SELECT * FROM “Blanks in Table Name”
or we can use ([])
SELECT * FROM [Blanks in Table Name]
56.
Prefix local temporary table names with single number sign (#table_name), and
prefix global temporary table names with a double number sign (##table_name).
Global temporary tables are automatically dropped when the session that created
the table ends and all other tasks have stopped referencing them.
26.joji said,
57.
Static cursors
Dynamic cursors
Forward-only cursors
Keyset-driven cursors
Static cursors detect few or no changes but consume relatively few resources
while scrolling, although they store the entire cursor in tempdb. Dynamic cursors
detect all changes but consume more resources while scrolling, although they
make the lightest use of tempdb. Keyset-driven cursors lie in between, detecting
most changes but at less expense than dynamic cursors.
27.Asok said,
29.Swathi said,
45.Database Normalization means organizing data into more than one table.
Normalization improves performance by reducing redundancy.
Data integrity ensures the consistency & correctness of data stored in a database.
5 types of constraints
1. PRIMARY constraint
2.FOREIGN constraint
3.UNIQUE constraint
4.CHECK constraint
5.DEFAULT constraint
5 types of constraints
1. PRIMARY constraint
2.FOREIGN constraint
3.UNIQUE constraint
4.CHECK constraint
5.DEFAULT constraint
36.Jimmy said,
The difference from REPLACE is that this function uses a position in the string to
make replacement rather than a pattern.
37.Palaksha said,
Dear Friends
Another Way to get all the table names from a database ,
execute this query
38.premanshu said,
Thanks a Lot. Please keep it updated. Readers are requested to post other
questions also.
All the best.
39.Madhumalar said,
To copy the data from one table to another without creating the script:
let us consider the #temp is one table having data and that has to be copied to
#globaltemp,
execute the following query:
40.Madhumalar said,
Hi Vinay,
Here’s the query to get the second largest salary in a table. Let us have the
employee table with salary as one of the column
41.Praba said,
Hi,
Please tell me how to select the second largest salary from a table? Thanks
42.Praba said,
43.yash said,
hello all,
How can BCP used effectivey? help me with syntax
44.Amit said,
Q) can u tell the command to get all table names from a database
A) select name from sysobjects where type = ‘u’
45.Amit said,
Q) Please tell me how to select the second largest salary from a table?
A) Select Top 1 from Employee where Salary Not IN ( select Top 1 from
Employee order by Salary Desc)
order by Salary Desc
46.bjack said,
47.Krishna said,
Hi Vinay,
here employee is the table name. sal is the column name in that table.
Select sal from employee where sal = ( select max(sal) from employee where sal
48.maruthuvel said,
What is advantage and Disadvantage for adding Default Constraint more than one
column for particular table .
I Want know the performance while constraint increases.
49.sankalp said,
select top 1 * from emp where empid not in (select top N-1 empid from emp order
by empsalary desc) order by empsalary desc
cheers,
Sankalp
50.Debjit said,
If you want to create the #global temp table and insert data from #temp table then
you can use the following query
51.Jaspreet said,
To find out the Nth highest salary in a table by using Inline View:
select top 1 * from (select top N * from emp order by salary desc) sal
order by sal.salary
52.Jaspreet said,
53.Jaspreet said,
—
Jaspreet Nagra
54.Jaspreet said,
Praba,
set rowcount 1
select 1 while @@rowcount > 0
delete city where 1
55.Jaspreet said,
56.Jaspreet said,
How Unique Key allow only one Null Value? … mean when NULL is not
comparable then how UNIQUE KEY compare nulls? as in ORACLE UNIQUE
KEY allows as many null whereas SQL Server allows one.
–
Jaspreet Nagra
57.Vishal said,
sp_tables
@table_type=”‘table’”
60.jasper said,
how to ge trid of the not null constraint if the table has already been created..?
Some of the Answers can be very long So trying to give only Short answers.
First :-
Maximum (tenth) Salry
Select *,sal From Emp X Where 10 =
(
Select Count(Distinct Sal) From Emp Where sal >=X.sal
)
Second: Constraint
CHECK
NOT NULL
UNIQUE
Primary KEy
References
Default
Third : Update all those where a column is divisble by 10 (I do not think there is
Mod function but % operator can be used)
Update tableName Set ColumnName = value
Where COL/10 = convert(int,Col)/10
Select Max(salary)
From Employee
Where salary
NOT IN (Select max(salary) From Employee)
64.Hemlata said,
To find out the second largest rown in the table the query is
65.Nivea said,
/*Example*/
67.Divya said,
All,
I want to create a recordset that selects from all tables in the database, I have a
Db, with over 20 tables in, all clones of each over, what is the select statment that
will enable this??
cheers
piers
70.Carl said,
71.Uday P said,
Hi Vinay,
To get the name of all the tables in a database you can use one of the following 3
methods.
1. SELECT * FROM INFORMATION_SCHEMA.TABLE
WHERE table_type = ‘BASE TABLE’
2. SELECT name FROM sysobjects
WHERE type = ‘U’
3. EXEC SP_TABLES
But this stored proc will give you all the system table names and view names as
well. So try the 1 and 2 query if you just want the user tables in a database.
Hi All,
How to find the views based on the table. Also I wanted to know all the views,
that uses the particular table, across the data bases, I mean to say, if some view in
other data base use this table , then how to find all the views based on a table
across all the data bases.
I appreciate your response.
Thanks
Syed Ali.
UPDATE
WHERE
KeyRow % 10 = 0
70. Can we rewrite subqueries into simple select statements or with joins?
Example?
*-> Noncorrelated subqueries that return a single value really have no need to be
converted to joins/derived tables.
*-> Noncorrelated subqueries that return many values with IN or NOT IN syntax
could yield great performance gain by conversion to simple select or derived
table:
*-> Correlated subqueries could (but not always) yield performance gains by
conversion to derived tables:
Original query 3 (correlated subquery):
– most recent order date per customer
– correlated subquery runs once for each row in Party: inefficient for large result
sets
SELECT
P.PartyID,
P.PartyName,
LastOrderDate = (SELECT Max(OrderDate) FROM Orders WHERE
OrderingPartyID = P.PartyID)
FROM
Party P
–For medium-to-large rowsets that don’t use all values from the base lookup
table, derived table performance can be improved if conditions can be added to
the derived table query that limit its result set to the right rows (or few extra
rows).
75.dev said,
76.dev said,
77.Afzal said,
78.Afzal said,
one of way of doing this is to copy paste the stored procedure code into Query
Analyzer and run Query execution plan. check which step is resource intensive
and also check if there are table scans etc.
79.Kumar said,
Hi this is kumar,
Is there any function/any procedure to know the exact location of a cursor in the
result set?
Advance Thanks
Kumar
80.Kumar said,
Hi Syed,
83.Novice said,
Which command using Query Analyzer will give you the version of SQL server
and operating system?
Ans: type the command EXEC_msver in the query analyzer and then press either
F5 or click the green triangle on the analyzer.
84.Ravi said,
Hi All,
Is there a way to find out max(salary) and min(salary) from a query. i.e i mean i
want the output as below in MS Access
Name Salary
xyz 50,000/- ‘Maximum Salary
zzz 5,000/- ‘Minimum Salary
hi Ravi
Query to find out max(salary) and min(salary) from a query?
Name Salary
xyz 50,000/- ‘Maximum Salary
zzz 5,000/- ‘Minimum Salary
=======================
Select Name,Salary from table1 where Salary =(select max(Salary) from table1)
UNION
Select Name,Salary from table1 where Salary =(select min(Salary) from table1)
86.Varsha said,
87.Shyam said,
—
Jaspreet Nagra
Ans: SET is used to assign value to a variable but SELECT is used to retrieve
value from either a variable or table.
Hope it will help you understand the use of SET and SELECT.
89.rajneesh said,
select MIN(salary)from try where salary in(select top2 salary from try order by
salary desc)
90.pravin said,
Hi
Q. What is the Difference between Primary key and Unique Key?
91.GOpendra said,
Could anyone please tell me that what will be the output of following query
92.Harry said,
thanks for sharing all those information. BUt i have one question to ask:
If there a way to linking two MS SQL database in different server? If yes, How it
can be done? or How to export data between MS SQL database in two different
server?
93.Sekhar said,
94.Chalapathi said,
I have table with two columns(both are int columns). I want to fetch max value in
each row comparing two columns, can any one tell me the simplest way for this.
I want to delete duplicate records from a table without using (3rd table,Unique
key column). i want to use corelated query to do this. So plz help for same.
96.Kalambasha said,
How to find who does not get last 3 months salary? in sql server query
Help me…
97.Kalambasha said,
How to find How many employee never will get last month salary?
My table structure are Empno,Empname,Salary,Month
Help me
98.Sureshk said,
here employee is the table name. sal is the column name in that table
100.Sivakumar R said,
After , I will go to configure the server then the following error occurred.
Regards,
R.Sivakumar
101.cool said,
Select Max(salary)
From Employee
Where salary
NOT IN (Select max(salary) From Employee)
102.Hashim SH said,
Hi all
can any one tell me how to insert multiple record into the table using single insert
stmt
& also how to select alternative records from the table.
104.rb said,
hi vinay
to get the table names from a database
SELECT TABLE_NAME from information_schema.tables
105.rb said,
SELECT MAX(salary)
FROM employees
WHERE salary
NOT IN (SELECT TOP (N-1) salary FROM employees ORDER BY salary
DESC)
thx
106.ANILKUMAR said,
What are the new features introduced in SQL Server 2000? What changed
between the previous version of SQL Server and the current version?
107.yogesh said,
Hi i am Yogesh
What are the new Feature of SQL server 2005 (Yukon) which are not in SQL
2000?
108.Muruganandam said,
To find third largest number from a table
hi,
here is stored procedure to select any record
for example to get second largest salary give input as 2
for fifth largest give 5 and execute it
– exec uspparticular 36
if (@@error 0)
select @@error
will be help ful to know error
and work as error trapping
to get no of row afected by last statement
use
select @@rowcount
hi tell me how can i convert xls file to sql table using sql command not by using
dts
i want particular sql command that can transport my data in xls file to sql table
hi
delete will delete one by one row and also return the no of row deleted
but truncate will drop table and recreate it
it will not return the no of rows deleted
hence truncate is faster then delete
hi jason
to copy data from one table to another jst use
select * into table2 from table1
Hi
U can Store The result in a table of Stored Procedure Which Is returning 1
recordSet as
117.Rahul said,
select top 1 * from (select top m * from employee order by job_id desc) job
order by job.job_id
118.Rahul said,
hi
select top 1 * from (select top 2 * from employee order by job_id desc) job
order by job.job_id
119.Balaji. A said,
Q No. 64:
cheers,
Balaji. A
select * from item where prize in(select max(prize) from item where prize not
in(select max(prize) from item));
121.Vidhya said,
122.Priyadarshan said,
123.shivraj said,
The another diff between Truncate and Delete is that Trucate reset the idendity
column while delete not.
124.Kejal said,
What is a table called, if it does not have neither Cluster nor Non-cluster Index?
125.muthu said,
127.sadu said,
128.Madhavi said,
Hi Jason,
You can insert/update into #temp table only when you create one. Create a temp
table using the Create statement and you can do all the data manipulation as a
regular table. Here is an example.
129.Vaishali said,
Hi all,
130.Sarat said,
People are making fun rather than giving appopriate answer to the query to find
the second largest salary in a table.Other viewers will be confused with
that.Please answer to the questions correctly/or keep on reading Question rather
than answering.
Q-12: Moreover with DELETE we can specify WHERE clause to delete selective
rows whereas with TRUNCATE we can’t.
Hi Dev,
The basic differences between Primary Key and Unique key are as follows.
3) A table can have only one PK but It can have any number of UNIQUE Key.
Thanks.
134.prakash said,
How can we get the top 10 rows of a table say’ emp’ out of total 50 rows?
please sent me the answer if you have /
136.Raveeananthan said,
Please send .net C# ASP.net VB.net Sql server 2000 interview question
137.Qaja said,
There are two ways to find the sencond highest salary in a table .The following
are the General format
–Using Top KeyWord
Select Top 1 * From [TableName]
where [ unique FiledName ] Not In
(Select Top N-1 [Unique Filed Name] From
TableName
Order By [FiledName — SAl] Desc)
Order By FieldName Desc
[…] Source: MS SQL Server interview questions Click for more. Lucky for me I
wasn’t asked such question. This one always gets asked. For a while the database
interview questions were limited to Oracle and generic database design questions.
This is a set of more than a hundred Microsoft SQL Server interview questions.
Some questions are open-ended, and some do not have answers. […]
139.Vinayagam said,
Hi,
I want nth max(salary)
140.Rajesh said,
To get the Top 10 records from the table ‘emp’:
141.Vamsi said,
Ans of Q.79
The table is called a Heap
Ans of Q.40
There are Two ways where we can get information from more than two tables one
way is JOIN and other way is subquery.
Subquery Is a SELECT Statement within other SELECT Statement.The Inner
SELECT statement is executed first and the result of the inner SELECT Statement
is evaluated with outer SELECT Statement
Thanks
Ans of Q.43
The difference is that WHERE operates on individual rows, while HAVING
operates on groups.
Typically you will have at least one column to GROUP BY, such as:
select cust_id
, count(distinct order_id) as orders
from sales
where order_date >= ‘2005-01-01′
group
by cust_id
having sum(order_amt) > 10000
This query returns the cust_id and number of orders for every customer who has
order totals of $10,000 or more (the HAVING condition) for orders made this year
(the WHERE condition).
Hi all,
This query gets the index names for the table ‘Customers’ of the Northwind
database.
hi ,
why cant we use sp_helpindex stroed proc
Naveen Kumar.
Hi friends,
Thanks,
Naveen Kumar.
hi all
how we create trigger and what is the basic use …..
if anybody know please help
thanks
150.krishna gupta said,
151.sashi said,
152.Dilip said,
Hi frnd can u tell me howo get 5th max slaary from emp table
153.sus said,
154.Amrit said,
155.Galih said,
156.nayeem said,
hi,
in a table on one column i have put identity.after adding few records i want to
remove identity.how can i do that?
157.Ravi said,
158.Ken said,
Question 102: How can you get @@error and @@rowcount at the same time?
Ans: select @@rowcount union all select @@error
Hi gurus,
160.ganesh said,
hi,
161.ganesh said,
hi
UNION is used to remove the duplicate values in a table and disply the data
UNION ALL is used to display all the values in a tablewithout remove duplication
162.Bakul said,
Hi,
I want to form a query which is rare.
I have a table which stores incidents with thier start and end date. Start and end
dates
may be same or may be different if incident is occurring over few consicutive
days.
From query I want to get the results that has incidents between two given days.
The
results should include a row for each day if the incident is occurring over more
than
one day during the selected days.
As an example, say I want to select incidents between 8-oct and 10-oct. There is
one
incident which is occuring from 7-oct to 11-oct, then in the results that incident
should
have total 3 rows for each date 8,9 and 10.
In db any incident has only one row with start date and end date, not a row for
each day.
Bakul
Is an arbitrary integer from 1 through 127 that represents information about the
invocation state of the error. A negative value for state defaults to 1.
– Source BOL
You can use values 0–127. These values are not used by SQL Server
________________________
Vidhya said,
Wrote on April 3, 2006 @ 5:33 am
165.vishal said,
Thanks,
Naveen Kumar.
168.abhi said,
o/p should be
is it possible to get this output without any unique rows… plz mail me
169.ivanrdgz said,
Answer to question:
select
UserName,
UserAge,
UserDept
from test
group by
UserName,
UserAge,
UserDept
having count(*) > 1
170.Ashok said,
Get n th largest sal , Just put any number at ‘n’
select max(sal) from salary s where n= (select count(distinct(sal)) where s.sal >
sal)
Hi all,
Hi Ravi,
if u have any further problem then send a mail to me. “its dgoyal04 in the gamil”.
select max(sal) from salary s where n= (select count(distinct(sal)) where s.sal >
sal)
r u already run and test this query or just post without test?????????????????
174.swati said,
begin
declare @a sysname
SELECT @a=COL_NAME(OBJECT_ID(’mparty’),1)
select substring(@a,1,7) from idtable
end
in this example i got result as
select ‘empid’ from idtable
while i required
select empid from idtable
thanking you
swati kulkarni
Navin -
Logshipping is different than replication. Logs can be shipped to standby server
where the database should be in no-recovery or standby mode. You can have
standby server ready when failure of primary server occurs or you can even use
standby server for read-only adhoc queryies by users in your organizatin to
distribute load and also use the same server in event of main server failure.
As for replication, there are 3 types of replication. Depending on the transactions
being performed and the requirement you may implement it.
–
Rakshit Patel
___________
Hi friends,
Thanks,
Naveen Kumar.
176.Noob said,
177.Kalpana said,
SELECT TOP 1 salary FROM (SELECT DISTINCT TOP N salary FROM emp
ORDER BY salary DESC) a ORDER BY salary
178.Kalpana said,
SELECT TOP 1 salary FROM (SELECT DISTINCT TOP N salary FROM emp
ORDER BY salary DESC) a ORDER BY salary
How do I view indexes on multiple tables in the DB, using a single script?
When I use sp_helpindex , I get indexes on that particular table. What I want to do
is, view indexes of mutiple tables