SlideShare a Scribd company logo
1 of 6
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 it
doesn’t contain any data of its own. Instead, a view is merely a preplanned mapping and
representation
of the data stored in tables. The plan is stored in the database in the form of a query. This
query calls for
data from some, but not necessarily all, columns to be retrieved from one or more tables.
CREATE VIEW KrishanView
AS
SELECT CustomerName, Contact, Phone
FROM 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 more
correctly 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)
AS
select * 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 so
6. 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 logic
9. 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;
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 TableName
where ColumnName < (select Max (ColumnName) from TableName)
For 2nd lowest select Min (ColumnName) from TableName
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
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_Detail
SET drivername='Raja' where driverid='DDDE000001'

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

ALTER TABLE TableName
ADD columnName DataType

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

ALTER TABLE TableName
DROP 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 :
1A2
2B1
3C2
4D3
write 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 a
B NULL
NULL c

43 Write a query that will return the output as :
a
B
c
select c1 from A where c1 is not null
union
select c2 from B where c2 is not null
44. 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)

More Related Content

What's hot (19)

Oracle 9i notes(kamal.love@gmail.com)
Oracle 9i  notes(kamal.love@gmail.com)Oracle 9i  notes(kamal.love@gmail.com)
Oracle 9i notes(kamal.love@gmail.com)
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
SQL Functions and Operators
SQL Functions and OperatorsSQL Functions and Operators
SQL Functions and Operators
 
Interacting with Oracle Database
Interacting with Oracle DatabaseInteracting with Oracle Database
Interacting with Oracle Database
 
Assg2 b 19121033-converted
Assg2 b 19121033-convertedAssg2 b 19121033-converted
Assg2 b 19121033-converted
 
10053 - null is not nothing
10053 - null is not nothing10053 - null is not nothing
10053 - null is not nothing
 
Technical
TechnicalTechnical
Technical
 
Migration
MigrationMigration
Migration
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
 
Mysql1
Mysql1Mysql1
Mysql1
 
Sql
SqlSql
Sql
 
SQL
SQLSQL
SQL
 
Oracle
OracleOracle
Oracle
 
Oracle: DDL
Oracle: DDLOracle: DDL
Oracle: DDL
 
Structured Query Language(SQL)
Structured Query Language(SQL)Structured Query Language(SQL)
Structured Query Language(SQL)
 
Database Oracle Basic
Database Oracle BasicDatabase Oracle Basic
Database Oracle Basic
 
Oracle training in hyderabad
Oracle training in hyderabadOracle training in hyderabad
Oracle training in hyderabad
 
Introduction to oracle optimizer
Introduction to oracle optimizerIntroduction to oracle optimizer
Introduction to oracle optimizer
 
MYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-havingMYSQL single rowfunc-multirowfunc-groupby-having
MYSQL single rowfunc-multirowfunc-groupby-having
 

Similar to Sql Queries

Introduction to MySQL - Part 2
Introduction to MySQL - Part 2Introduction to MySQL - Part 2
Introduction to MySQL - Part 2webhostingguy
 
ii bcom dbms SQL Commands.docx
ii bcom dbms SQL Commands.docxii bcom dbms SQL Commands.docx
ii bcom dbms SQL Commands.docxlakshmi77
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasadpaddu123
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasadpaddu123
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql newSANTOSH RATH
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIMsKanchanaI
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQueryAbhishek590097
 
Database object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab AssignmentDatabase object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab AssignmentArun Sial
 

Similar to Sql Queries (20)

Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
Mysqlppt
MysqlpptMysqlppt
Mysqlppt
 
DBMS.pdf
DBMS.pdfDBMS.pdf
DBMS.pdf
 
Introduction to MySQL - Part 2
Introduction to MySQL - Part 2Introduction to MySQL - Part 2
Introduction to MySQL - Part 2
 
MULTIPLE TABLES
MULTIPLE TABLES MULTIPLE TABLES
MULTIPLE TABLES
 
ii bcom dbms SQL Commands.docx
ii bcom dbms SQL Commands.docxii bcom dbms SQL Commands.docx
ii bcom dbms SQL Commands.docx
 
Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
 
Mysql
MysqlMysql
Mysql
 
Mysql
MysqlMysql
Mysql
 
Mysql
MysqlMysql
Mysql
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
Its about a sql topic for basic structured query language
Its about a sql topic for basic structured query languageIts about a sql topic for basic structured query language
Its about a sql topic for basic structured query language
 
Interview Questions.pdf
Interview Questions.pdfInterview Questions.pdf
Interview Questions.pdf
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Database object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab AssignmentDatabase object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab Assignment
 
Chapter8 my sql revision tour
Chapter8 my sql revision tourChapter8 my sql revision tour
Chapter8 my sql revision tour
 
Mysql cheatsheet
Mysql cheatsheetMysql cheatsheet
Mysql cheatsheet
 

Recently uploaded

Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 

Recently uploaded (20)

LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 

Sql Queries

  • 1. 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 it doesn’t contain any data of its own. Instead, a view is merely a preplanned mapping and representation of the data stored in tables. The plan is stored in the database in the form of a query. This query calls for data from some, but not necessarily all, columns to be retrieved from one or more tables.
  • 2. CREATE VIEW KrishanView AS SELECT CustomerName, Contact, Phone FROM 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 more correctly 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) AS select * 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 so 6. 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 logic 9. 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;
  • 3. 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 TableName where ColumnName < (select Max (ColumnName) from TableName) For 2nd lowest select Min (ColumnName) from TableName
  • 4. 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
  • 5. 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_Detail SET drivername='Raja' where driverid='DDDE000001' 36. Write a command to add a new column to a table. ALTER TABLE TableName ADD columnName DataType 37. Write a command to remove a column to a table. ALTER TABLE TableName DROP 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 : 1A2
  • 6. 2B1 3C2 4D3 write 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 a B NULL NULL c 43 Write a query that will return the output as : a B c select c1 from A where c1 is not null union select c2 from B where c2 is not null 44. 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)