Vous êtes sur la page 1sur 13

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 31/12/1975;

BETWEEN 01/01/1960 AND

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

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

DOB BETWEEN

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 upper('joe%'); WHERE upper(EmpName) like

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 Unique key can accept only one null value. values. By default, Primary key is clustered By default, index and data in the database Unique key is a table is physically organized in the unique nonsequence of clustered index. clustered index. We can have only one Primary key We can have more than one unique key in a table. in a table. Primary key can be made foreign In SQL Server, Unique key can be made foreign key into key into another table. another table.

Define Primary key and Unique key


1. 2. 3. 4. 5. CREATE TABLE Employee ( EmpID int PRIMARY KEY, --define primary key Name varchar (50) NOT NULL, MobileNo int UNIQUE, --define unique key

6. )

Salary int NULL

Query to get nth(3rd) Highest Salary


7. 8. 9. Select TOP 1 Salary as '3rd Highest Salary' from (SELECT DISTINCT TOP 3 Salary from Employee ORDER BY Salary DESC) a ORDER BY Salary ASC

Query to get nth(3rd) Lowest Salary


1. 2. 3. Select TOP 1 Salary as '3rd Lowest Salary' from (SELECT DISTINCT TOP 3 Salary from Employee ORDER BY Salary ASC) a ORDER BY Salary DESC

Primary Key Primary key uniquely identify a record in the table. Primary Key can't accept null Foreign key can accept multiple null value. values. By default, Primary key is Foreign key do not automatically create an index, clustered or

Difference between Primary Key & Foreign Key Foreign Key Foreign key is a field in the table that is primary key in another table.

clustered index and data in the database table is physically organized in the sequence of clustered index. We can have only one Primary key in a table.

non-clustered. You can manually create an index on foreign key.

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

Define Primary key and Foreign key


10. --Create Parent Table 11. CREATE TABLE Department 12. ( 13. DeptID int PRIMARY KEY, --define primary key 14. 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 key 22. Name varchar (50) NOT NULL, 23. Salary int NULL, 24. --define foreign key 25. DeptID int FOREIGN KEY REFERENCES Department(DeptID) 26. )

Note
As @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. 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 data INSERT 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 Join
This 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 Example


27. SELECT * FROM tblEmp JOIN tblDept 28. ON tblEmp.DeptID = tblDept.DeptID; Inner Join Result tblEmp.Name tblEmp.DeptID Ram 1 Raju 2 Soya 2 Sam 3

tblDept.Name HR IT IT ADMIN

tblDept.Dep 1 2 2 3

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

Equi Join
Equi 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 Example


7. 8. 9. 10. 11. SELECT * FROM tblEmp JOIN tblDept ON tblEmp.DeptID = tblDept.DeptID; --Using Caluse is supported in SQL Server --Oracle and MySQL Query SELECT * FROM tblEmp INNER JOIN tblDept USING(DeptID) Equi Join Result tblEmp.Name tblEmp.DeptID tblDept.Name Ram 1 HR Raju 2 IT Soya 2 IT Sam 3 ADMIN

tblDept.Dep 1 2 2 3

Note
Inner 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 join The USING clause is not supported by SQL Server and Sybase. This clause is supported by Oracle and MySQL.

Natural Join
Natural 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 SELECT * FROM tblEmp NATURAL JOIN tblDept Natural 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.

Note

In 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 Forms
We 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.

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 key 1NF of above UNF table is as follows:

30.

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. 2NF of above 1NF tables is as follows:

32.

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. 3NF of above 2NF tables is as follows:

34.

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: Remove the non trival functional dependency.

36.

Make separate table for the determinants. 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.

38. 39.

4NF of below table is as follows:

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.

5NF of below table is as follows:

Vous aimerez peut-être aussi