Sql Queries

9
1. Write complete select commnad in sql server 2005. SELECT [ALL | DISTINCT] columnname1 [,columnname2] FROM tablename1 [,tablename2] [WHERE condition] [ and|or condition...] [GROUP BY column-list] [HAVING "conditions] [ORDER BY "column-list" [ASC | DESC] ] 2. Write a select command which selects top 10 rows from a table. SELECT TOP 10 * from Tablename 3. Write a select command which selects 10 rows on random basis from a table. SELECT TOP 10 * from Tablename ORDER BY newid() newid is the function which generates a unique 36 character id for each row in the resul set and every time u execute the query this newid() function generates a new unique id for each row * 4. What are differenet types of joins? 5. What is Outer Join? 6. Tell Differnece between outer and inner join. 7. Tell diffenece between Left Outer Join and Right Outer Join. Left outer joins include all of the records from the first (left) of two tables, even if there are no matching values for records in the second (right) table. select * from table1 LEFT OUTER JOIN table2 ON table1.CommonColumn=table2.CommonColumn Right outer joins include all of the records from the second (right) of two tables, even if there are no matching values for records in the first (left) table. select * from table1 RIGHT OUTER JOIN table2 ON table1.CommonColumn=table2.CommonColumn 8. What is full outer join?

description

 

Transcript of Sql Queries

Page 1: Sql Queries

1. Write complete select commnad in sql server 2005.

SELECT [ALL | DISTINCT] columnname1 [,columnname2]FROM tablename1 [,tablename2][WHERE condition] [ and|or condition...][GROUP BY column-list][HAVING "conditions][ORDER BY "column-list" [ASC | DESC] ]

2. Write a select command which selects top 10 rows from a table.

SELECT TOP 10 * from Tablename

3. Write a select command which selects 10 rows on random basis from a table.

SELECT TOP 10 * from Tablename ORDER BY newid() newid is the function which generates a unique 36 character id for each row in the resul set and every time u execute the query this newid() function generates a new unique id for each row *4. What are differenet types of joins?5. What is Outer Join?6. Tell Differnece between outer and inner join.

7. Tell diffenece between Left Outer Join and Right Outer Join.

Left outer joins include all of the records from the first (left) of two tables, even if there are no matching values for records in the second (right) table. select * from table1 LEFT OUTER JOIN table2 ON table1.CommonColumn=table2.CommonColumn Right outer joins include all of the records from the second (right) of two tables, even if there are no matching values for records in the first (left) table. select * from table1 RIGHT OUTER JOIN table2 ON table1.CommonColumn=table2.CommonColumn

8. What is full outer join?

Full outer joins include all of the records from both tables, even if there are no matching values for records in the other table. Syntax....... select * from tableName FULL OUTER JOIN table2 ON table1.CommonColumn=table2.CommonColumn

9. What is a view ? Write syntax to create view.

A view is something of a virtual table. A view, for the most part, is used just like a table, except that itdoesn’t contain any data of its own. Instead, a view is merely a preplanned mapping and representationof the data stored in tables. The plan is stored in the database in the form of a query. This query calls fordata from some, but not necessarily all, columns to be retrieved from one or more tables.

Page 2: Sql Queries

CREATE VIEW KrishanViewASSELECT CustomerName, Contact, PhoneFROM Customers

10. What are benefits of view?

11. What is a stored procedure. Write one.

a stored procedure is really just something of a script—or morecorrectly speaking, a batch—that is stored in the database rather than in a separate file. A stored procedure is a precompiled set of sql statements. /* create stored procedure that will return all the rows based on a particular name */CREATE PROC sp1 @namevariable nvarchar(10)ASselect * from tablename where name=@namevariable /*to run stored procedure */ EXEC sp1 'ram'

12. How many type of parameters a stored procedure can have?

Two types : Input Parameter and Output parameter.

13. What are differences between a function and a stored procedure?

Stored Procedure :supports deffered name resoultion Example while writing a stored procedure that uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation but runtime throws errorFunction wont support deffered name resolution. 2. Stored procedure returns always integer value by default zero. where as function return type could be scalar or table or table values(SQL Server).3. Stored Procedure is pre compiled exuction plan where as functions are not.4. Stored Procedure retuns more than one value at a time while funtion returns only one value at a time.5. We can call the functions in sql statements (select max(sal) from emp). where as sp is not so6. Function do not return the images,text whereas sp returns all.7. Function and sp both can return the values. But function returns 1 value only.procedure can return multiple values(max. 1024) we can select the fields from function. in the case of procdure we cannot select the fields.8. Functions are used for computations where as procedures can be used for performing business logic9. Functions MUST return a value, procedures need not be.10. You can have DML(insert, update, delete) statements in a function. But, you cannot call such a function in a SQL query..eg: suppose, if u have a function that is updating a table.. you can't call that function in any sql query.- select myFunction(field) from sometable;

Page 3: Sql Queries

will throw error.11. Function parameters are always IN, no OUT is possible

14. What are triggers ?How many types of triggers are there?

Triggers are pieces of code that you attach to a particular table or view. They get fired automatically when an opration occurs on that table like insert,delete or update . Moreover triggers are fired implecitely and they cannot be called explicitely. 1. INSERT triggers – are piece of code attached to a table or view that is fired when insert operation is performed on that table or view. 2. DELETE triggers- are piece of code attached to a table or view that is fired when insert operation is performed on that table or view. 3. UPDATE triggers - are piece of code attached to a table or view that is fired when insert operation is performed on that table or view.

15. What are differnces between stored procedure and a trigger?1. Triggers are fired implicitly where there a change in the database. Where as SP are fired only when a call is made ti it.2. we can write a stored procedure within a trigger bu cannot write a trigger within a stored procedure.

16. If a delete trigger is defined on a table and it has a delete command in it. Then how many times the delete trigger will be fired if a delete command is fired?

Only one time as triggers are called implecitely....

17. What are cursors?

If possible, avoid using SQL Server cursors. They generally use a lot of SQL Server resources and reduce the performance and scalability of your applications. If you need to perform row-by-row operations, try to find another method to perform the task.Here are some alternatives to using a cursor:

Use WHILE LOOPS Use temp tables Use derived tables Use correlated sub-queries Use the CASE statement Perform multiple queries

18. Tell the benefits of cursors.

19. Write a command to select 2nd highest/lowest record from a column of a table.

For 2nd highest select Max (ColumnName) from TableNamewhere ColumnName < (select Max (ColumnName) from TableName)For 2nd lowest select Min (ColumnName) from TableName

Page 4: Sql Queries

where ColumnName > (select Min (ColumnName) from TableName)

20. Write a command which will copy the data as well as structure of a table after creating a new table.

SELECT * INTO NewTableName From ExistingTableName

21. Write a command that will copy only structure of a table into a new table.

SELECT * INTO NewTableName From ExistingTableName WHERE 1>2

22. Write a command which will copy only the record of the table into a present table.(if both the tables have same structure)

INSERT INTO TABLE1 SELECT * FROM TABLE2

23. Write a command to retrieve data from a column after removing duplicacy.

SELECT DISTINCT(ColumnName) FROM TABLENAME

24. Write a command that will count total number of rows from a table.

SELECT COUNT(*) FROM TABLENAME

25. Write a commnad that will return total number of distinct items in a column from a table.

SELECT COUNT( DISTINCT ColumnName ) FROM TABLENAME

26. Write a command that will return the names of all the tables present in a single database.

SELECT table_name FROM INFORMATION_SCHEMA.TABLES

27. Write a command that will return total number of tables present in a table.

SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES

28. Write a command that will return the total number of columns present in a table.

SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS

29. Write a command that will return the names of all the columns present in a single database.

SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS

Page 5: Sql Queries

30. Write a command that will return data from a table based on NULL values of a column.

SELECT * FROM TableName WHERE ColumnName Is NULL

31. Write a command that will return the structure of the table.

sp_help TableName /* sp_help is a predefined stored procedure to do the task*/

32. Write a command that will rename the table.

sp_rename 'OldTableName' , 'NewTableName'

33. Write a command to delete data from a table.

DELETE TableName

34. Write a command to insert data into a table.

INSERT Into TanleName ( Col1,Col2,Col3,Col4......) Values ('val1','val2','val3','val4' )

35. Write a command to update data into a table.

UPDATE Driver_DetailSET drivername='Raja' where driverid='DDDE000001'

36. Write a command to add a new column to a table.

ALTER TABLE TableNameADD columnName DataType

37. Write a command to remove a column to a table.

ALTER TABLE TableNameDROP COLUMN columnName

38. Write a command to rename a column 'empname' of a table 'Employee' to 'EmpName' sp_rename

'Employee.empname', 'EmpName', 'COLUMN'

39. there is a table named ‘employee’ having three columns : empid int ,empname nchar(20),managerid int.It has following data : 1 A 2

Page 6: Sql Queries

2 B 13 C 24 D 3write a query that will display all the employee name and there corresponding manager names . select ‘Employee Name’=emp1.name , ‘Employee Name’=emp2.name from employee emp1 join employee emp2 on emp1.managerid=emp2.empid

40. take the table given in the question above and write a query that will give the output as like :

A,B,C,D i.e. horizontalally.

41.There is a table having 20 rows inside it.Write a command that will extract the rows between the 5th record and 10 th row of the table.

Select * from tableA where col1 not in(select top 5 col1 from tableA) and col1 in(select top 10 col1 from tableA)

42.there are two tables a and b having only two columns c1 and c2 respectively.

Table a has data such like that table b has null values against the data in table a.Eg.Table A Table B

..c1.......... .c2............NULL aB NULLNULL c

43 Write a query that will return the output as : aBcselect c1 from A where c1 is not nullunion select c2 from B where c2 is not null44. write a sql query to get fifth highest salary from the table.select top 1 salary from tableA where salary in(select top 5 salary from tableA order by salary desc)