question 1

16
Question 1: SQL Query to find second highest salary of Employee Answer : There are many ways to find second highest salary of Employee in SQL, you can either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery : select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee ); See How to find second highest salary in SQL for more ways to solve this problem. Question 2: SQL Query to find Max Salary from each department. Answer : SELECT DeptID, MAX(Salary) FROM Employee GROUP BY DeptID. Question 3:Write SQL Query to display current date. Ans:SQL has built in function called GetDate() which returns current timestamp. SELECT GetDate(); Question 4:Write an SQL Query to check whether date passed to Query is date of given format or not. Ans: SQL has IsDate() function which is used to check passed value is date or not of specified format ,it returns 1(true) or 0(false) accordingly. SELECT ISDATE('1/08/13') AS "MM/DD/YY";

Upload: iveraj

Post on 30-Nov-2015

22 views

Category:

Documents


2 download

DESCRIPTION

Question1

TRANSCRIPT

Page 1: Question 1

Question 1: SQL Query to find second highest salary of Employee

Answer : There are many ways to find second highest salary of Employee in SQL, you can either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery :

select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee ); 

See How to find second highest salary in SQL for more ways to solve this problem.

Question 2: SQL Query to find Max Salary from each department.

Answer :

SELECT DeptID, MAX(Salary) FROM Employee  GROUP BY DeptID. 

Question 3:Write SQL Query to display current date.

 Ans:SQL has built in function called GetDate() which returns current timestamp.

SELECT GetDate(); 

Question 4:Write an SQL Query to check whether date passed to Query is date of given format or not.

Ans: SQL has IsDate() function which is used to check passed value is date or not of specified format ,it returns 1(true) or 0(false) accordingly.

SELECT  ISDATE('1/08/13') AS "MM/DD/YY"; 

It will return 0 because passed date is not in correct format.

Question 5: Write a SQL Query to print the name of distinct employee whose DOB is between 01/01/1960 to 31/12/1975.

Ans:SELECT DISTINCT EmpName FROM Employees WHERE DOB  BETWEEN ‘01/01/1960’ AND ‘31/12/1975’;

Question 6:Write an SQL Query find number of employees according to gender  whose DOB is between 01/01/1960 to 31/12/1975.

Page 2: Question 1

Answer : SELECT COUNT(*), sex from Employees  WHERE  DOB BETWEEN ‘01/01/1960 ' AND ‘31/12/1975’  GROUP BY sex;

Question 7:Write an SQL Query to find employee whose Salary is equal or greater than 10000.

Answer : SELECT EmpName FROM  Employees WHERE  Salary>=10000;

Question 8:Write an SQL Query to find name of employee whose name Start with ‘M’

Ans: SELECT * FROM Employees WHERE EmpName like 'M%';

Question 9: find all Employee records containing the word "Joe", regardless of whether it was stored as JOE, Joe, or joe.

Answer : SELECT  * from Employees  WHERE  upper(EmpName) like upper('joe%');

Question 10: Write a SQL Query to find  year from date.

Answer :  SELECT YEAR(GETDATE()) as "Year";

Difference between Primary Key & Unique Key

Primary Key Unique Key

Primary Key can't accept null values.

Unique key can accept only one null value.

By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.

By default, Unique key is a unique non-clustered index.

We can have only one Primary key in a table.

We can have more than one unique key in a table.

Primary key can be made foreign key into another table.

In SQL Server, Unique key can be made foreign key into another table.

Define Primary key and Unique key1. CREATE TABLE Employee 2. (

Page 3: Question 1

3. EmpID int PRIMARY KEY, --define primary key4. Name varchar (50) NOT NULL,5. MobileNo int UNIQUE, --define unique key6. Salary int NULL )

Query to get nth(3rd) Highest Salary7. Select TOP 1 Salary as '3rd Highest Salary' 8. from (SELECT DISTINCT TOP 3 Salary from Employee ORDER BY

Salary DESC) 9. a ORDER BY Salary ASC

Query to get nth(3rd) Lowest Salary1. Select TOP 1 Salary as '3rd Lowest Salary' 2. from (SELECT DISTINCT TOP 3 Salary from Employee ORDER BY

Salary ASC) 3. a ORDER BY Salary DESC

 

Difference between Primary Key & Foreign Key

Primary Key Foreign Key

Primary key uniquely identify Foreign key is a field in the table that is primary key in another table.

Page 4: Question 1

a record in the table.

Primary Key can't accept null values.

Foreign key can accept multiple null value.

By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.

Foreign key do not automatically create an index, clustered ornon-clustered. You can manually create an index on foreign key.

We can have only one Primary key in a table.

We can have more than one foreign key in a table.

Define Primary key and Foreign key10. --Create Parent Table 11. CREATE TABLE Department 12. (13. DeptID int PRIMARY KEY, --define primary key14. Name varchar (50) NOT NULL,15. Address varchar(100) NULL 16. )17. GO 18. --Create Child Table 19. CREATE TABLE Employee 20. (21. EmpID int PRIMARY KEY, --define primary key22. Name varchar (50) NOT NULL,23. Salary int NULL,24. --define foreign key25. DeptID int FOREIGN KEY REFERENCES Department(DeptID)26. )

NoteAs @Marc Jellinek suggested, I would like to add the below points about foreign key :4.Foreign keys do not automatically create an index, clustered or nonclustered. You must

manually create an index on foreign keys.5.There are actual advantages to having a foreign key be supported with a clustered

index, but you get only one per table. What's the advantage? If you are selecting the parent plus all child records, you want the child records next to each other. This is easy to accomplish using a clustered index.

6.Having a null foreign key is usually a bad idea. In the example below, the record in [dbo].[child] is what would be referred to as an "orphan record". Think long and hard before doing this.

Page 5: Question 1

IF EXISTS (SELECT * FROM [sys].[schemas] [sch] INNER JOIN [sys].[tables] [tbl] ON [sch].[schema_id] = [tbl].[schema_id] WHERE [sch].[name] = 'dbo' AND [tbl].[name] = 'child')

DROP TABLE [dbo].[child] IF EXISTS (SELECT * FROM [sys].[schemas] [sch] INNER JOIN [sys].

[tables] [tbl] ON [sch].[schema_id] = [tbl].[schema_id] WHERE [sch].[name] = 'dbo' AND [tbl].[name] = 'parent') DROP TABLE [dbo].[parent]

CREATE TABLE [dbo].[parent]( [id] [int] IDENTITY NOT NULL, [name] [varchar](250) NOT NULL, CONSTRAINT [PK_dbo__parent] PRIMARY KEY NONCLUSTERED ([id])) CREATE TABLE [dbo].[child]([id] [int] IDENTITY NOT NULL, [parent_id] [int] NULL, [name] [varchar](250) NOT NULL, CONSTRAINT [PK_dbo__child] PRIMARY KEY NONCLUSTERED ([id]), CONSTRAINT [FK_dbo__child__dbo__parent] FOREIGN KEY ([parent_id])

REFERENCES [dbo].[parent]([id])) --Insert dataINSERT INTO [dbo].[parent] ([name]) VALUES ('parent1')INSERT INTO [dbo].[child] ([parent_id], [name])VALUES(1, 'child

1')INSERT INTO [dbo].[child] ([parent_id], [name])VALUES(NULL, 'child

2') --Select data SELECT * FROM [dbo].[child]

SQL join clause is used to to retrieve data from two or more database tables. In previous article, I have explained the Different Types of SQL Joins. In this article, I would explain the difference among inner join, equi join and natural join.

Inner JoinThis is the most used join in the SQL. this join returns only those records/rows that match/exists in both the database tables.Inner Join Example27. SELECT * FROM tblEmp JOIN tblDept28. ON tblEmp.DeptID = tblDept.DeptID;

Inner Join Result

Page 6: Question 1

tblEmp.Name tblEmp.DeptID tblDept.Name tblDept.DeptID

Ram 1 HR 1

Raju 2 IT 2

Soya 2 IT 2

Sam 3 ADMIN 3

In the join condition, you can also use other operators like <,>,<>.

Equi JoinEqui join is a special type of join in which we use only equality operator. Hence, when you make a query for join using equality operator then that join query comes under Equi join.Equi Join Example7. SELECT * FROM tblEmp JOIN tblDept8. ON tblEmp.DeptID = tblDept.DeptID;9. --Using Caluse is supported in SQL Server10. --Oracle and MySQL Query11. SELECT * FROM tblEmp INNER JOIN tblDept USING(DeptID)

Equi Join Result

tblEmp.Name tblEmp.DeptID tblDept.Name tblDept.DeptID

Ram 1 HR 1

Raju 2 IT 2

Soya 2 IT 2

Sam 3 ADMIN 3

NoteInner join can have equality (=) and other operators (like <,>,<>) in the join condition.Equi join only have equality (=) operator in the join condition.-Equi join can be an Inner join, Left Outer join, Right Outer joinThe USING clause is not supported by SQL Server and Sybase. This clause is supported

by Oracle and MySQL.

Natural JoinNatural join is a type of equi join which occurs implicitly by comparing all the same names columns in both tables. The join result have only one column for each pair of equally named columns.Natural Join Example--Run in Oracle and MySQL

Page 7: Question 1

SELECT * FROM tblEmp NATURAL JOIN tblDeptNatural Join Result

DeptID tblEmp.Name tblDept.Name

1 Ram HR

2 Raju IT

2 Soya IT

3 Sam ADMIN

In the above join result we have only one column "DeptID" for each pair of equally named columns.

NoteIn Natural join, you can't see what columns from both the tables will be used in the join. In

Natural join, you might not get the desired result what you are expecting.Natural join clause is not supported by SQL Server, it is supported by Oracle and MySQL

Normalization or data normalization is a process to organize the data into tabular format (database tables). A good database design includes the normalization, without normalization a database system may slow, inefficient and might not produce the expected result. Normalization reduces the data redundancy and inconsistent data dependency.

Normal FormsWe organize the data into database tables by using normal forms rules or conditions. Normal forms help us to make a good database design. Generally we organize the data up to third normal form. We rarely use the fourth and fifth normal form.To understand normal forms consider the folowing unnormalized database table. Now we will normalize the data of below table using normal forms.

Page 8: Question 1

29. First Normal Form (1NF)A database table is said to be in 1NF if it contains no repeating fields/columns. The process of converting the UNF table into 1NF is as follows:

Separate the repeating fields into new database tables along with the key from unnormalized database table.

The primary key of new database tables may be a composite key30. 1NF of above UNF table is as follows:

Page 9: Question 1

31. Second Normal Form (2NF)A database table is said to be in 2NF if it is in 1NF and contains only those fields/columns that are functionally dependent(means the value of field is determined by the value of another field(s)) on the primary key. In 2NF we remove the partial dependencies of any non-key field.The process of converting the database table into 2NF is as follows:

Remove the partial dependencies(A type of functional dependency where a field is only functionally dependent on the part of primary key) of any non-key field.

If field B depends on field A and vice versa. Also for a given value of B, we have only one possible value of A and vice versa, Then we put the field B in to new database table where B will be primary key and also marked as foreign key in parent table.

Page 10: Question 1

32. 2NF of above 1NF tables is as follows:

33. Third Normal Form (3NF)A database table is said to be in 3NF if it is in 2NF and all non keys fields should be dependent on primary key or We can also said a table to be in 3NF if it is in 2NF and no fields of the table is transitively functionally dependent on the primary key.The process of converting the table into 3NF is as follows:

Remove the transitive dependecies(A type of functional dependency where a field is functionally dependent on the Field that is not the primary key.Hence its value is determined, indirectly by the primary key )

Make separate table for transitive dependent Field.

Page 11: Question 1

34. 3NF of above 2NF tables is as follows:

35. Boyce Code Normal Form (BCNF)A database table is said to be in BCNF if it is in 3NF and contains each and every determinant as a candidate key.The process of converting the table into BCNF is as follows:

Page 12: Question 1

Remove the non trival functional dependency.Make separate table for the determinants.

36. BCNF of below table is as follows:

37. Fourth Normal Form (4NF)A database table is said to be in 4NF if it is in BCNF and primary key has one-to-one relationship to all non keys fields or We can also said a table to be in 4NF if it is in BCNF and contains no multi-valued dependencies.The process of converting the table into 4NF is as follows:

Remove the multivalued dependency.Make separate table for multivalued Fields.

Page 13: Question 1

38. 4NF of below table is as follows:39. Fifth Normal Form (5NF)A database table is said to be in 5NF if it is

in 4NF and contains no redundant values or We can also said a table to be in 5NF if it is in 4NF and contains no join dependencies.The process of converting the table into 5NF is as follows:

Remove the join dependency.Break the database table into smaller and smaller tables to remove all data

redundancy.

Page 14: Question 1

5NF of below table is as follows: