TERADATA SQL-4

Joins - SQL interview Questions - Edureka

Image result for types of joins

 

Image result for types of joins

 

Image result for types of joins

ANSI-standard SQL specifies five types of JOIN clauses as follows:

  • INNER JOIN (a.k.a. “simple join”): Returns all rows for which there is at least one match in BOTH tables. This is the default type of join if no specific JOIN type is specified.
  • LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table, and the matched rows from the right table; i.e., the results will contain all records from the left table, even if the JOIN condition doesn’t find any matching records in the right table. This means that if the ON clause doesn’t match any records in the right table, the JOIN will still return a row in the result for that record in the left table, but with NULL in each column from the right table.
  • RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table, and the matched rows from the left table. This is the exact opposite of a LEFT JOIN; i.e., the results will contain all records from the right table, even if the JOIN condition doesn’t find any matching records in the left table. This means that if the ON clause doesn’t match any records in the left table, the JOIN will still return a row in the result for that record in the right table, but with NULL in each column from the left table.
  • FULL JOIN (or FULL OUTER JOIN): Returns all rows for which there is a match in EITHER of the tables. Conceptually, a FULL JOINcombines the effect of applying both a LEFT JOIN and a RIGHT JOIN; i.e., its result set is equivalent to performing a UNION of the results of left and right outer queries.
  • CROSS JOIN: Returns all records where each row from the first table is combined with each row from the second table (i.e., returns the Cartesian product of the sets of rows from the joined tables). Note that a CROSS JOIN can either be specified using the CROSS JOIN syntax (“explicit join notation”) or (b) listing the tables in the FROM clause separated by commas without using a WHERE clause to supply join criteria (“implicit join notation”).

 

What is the difference between inner and outer join? Explain with example.

Inner Join

Inner join returns rows when there is at least one match in both tables

If none of the record matches between two tables, then INNER JOIN will return a NULL set. Below is an example of INNER JOIN and the resulting set.

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE 
FROM DEPT dept, EMPLOYEE emp
WHERE emp.dept_id = dept.id
Department Employee
HR Inno
HR Privy
Engineering Robo
Engineering Hash
Engineering Anno
Engineering Darl
Marketing Pete
Marketing Meme
Sales Tomiti
Sales Bhuti

Outer Join

Outer Join, on the other hand, will return matching rows from both tables as well as any unmatched rows from one or both the tables (based on whether it is single outer or full outer join respectively).

Outer Join can be full outer or single outer

Notice in our record set that there is no employee in the department 5 (Logistics). Because of this if we perform inner join, then Department 5 does not appear in the above result. However in the below query we perform an outer join (dept left outer join emp), and we can see this department.

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE 
FROM DEPT dept, EMPLOYEE emp
WHERE dept.id = emp.dept_id (+)
Department Employee
HR Inno
HR Privy
Engineering Robo
Engineering Hash
Engineering Anno
Engineering Darl
Marketing Pete
Marketing Meme
Sales Tomiti
Sales Bhuti
Logistics

The (+) sign on the emp side of the predicate indicates that emp is the outer table here. The above SQL can be alternatively written as below (will yield the same result as above):

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE 
FROM DEPT dept LEFT OUTER JOIN EMPLOYEE emp
ON dept.id = emp.dept_id  

What is the difference between JOIN and UNION?

SQL JOIN allows us to “lookup” records on other table based on the given conditions between two tables. For example, if we have the department ID of each employee, then we can use this department ID of the employee table to join with the department ID of department table to lookup department names.

UNION operation allows us to add 2 similar data sets to create resulting data set that contains all the data from the source data sets. Union does not require any condition for joining. For example, if you have 2 employee tables with same structure, you can UNION them to create one result set that will contain all the employees from both of the tables.

SELECT * FROM EMP1
UNION
SELECT * FROM EMP2;

What is the difference between UNION and UNION ALL?

UNION and UNION ALL both unify for add two structurally similar data sets, but UNION operation returns only the unique records from the resulting data set whereas UNION ALL will return all the rows, even if one or more rows are duplicated to each other.

In the following example, I am choosing exactly the same employee from the emp table and performing UNION and UNION ALL. Check the difference in the result.

SELECT * FROM EMPLOYEE WHERE ID = 5
UNION ALL
SELECT * FROM EMPLOYEE WHERE ID = 5
ID MGR_ID DEPT_ID NAME SAL DOJ
5.0 2.0 2.0 Anno 80.0 01-Feb-2012
5.0 2.0 2.0 Anno 80.0 01-Feb-2012
SELECT * FROM EMPLOYEE WHERE ID = 5
UNION 
SELECT * FROM EMPLOYEE WHERE ID = 5
ID MGR_ID DEPT_ID NAME SAL DOJ
5.0 2.0 2.0 Anno 80.0 01-Feb-2012

What is the difference between WHERE clause and HAVING clause?

WHERE and HAVING both filters out records based on one or more conditions. The difference is, WHERE clause can only be applied on a static non-aggregated column whereas we will need to use HAVING for aggregated columns.

To understand this, consider this example.
Suppose we want to see only those departments where department ID is greater than 3. There is no aggregation operation and the condition needs to be applied on a static field. We will use WHERE clause here:

SELECT * FROM DEPT WHERE ID > 3
ID NAME
4 Sales
5 Logistics

Next, suppose we want to see only those Departments where Average salary is greater than 80. Here the condition is associated with a non-static aggregated information which is “average of salary”. We will need to use HAVING clause here:

SELECT dept.name DEPARTMENT, avg(emp.sal) AVG_SAL
FROM DEPT dept, EMPLOYEE emp
WHERE dept.id = emp.dept_id (+)
GROUP BY dept.name
HAVING AVG(emp.sal) > 80
DEPARTMENT AVG_SAL
Engineering 90

As you see above, there is only one department (Engineering) where average salary of employees is greater than 80.

What is the difference among UNION, MINUS and INTERSECT?

UNION combines the results from 2 tables and eliminates duplicate records from the result set.

MINUS operator when used between 2 tables, gives us all the rows from the first table except the rows which are present in the second table.

INTERSECT operator returns us only the matching or common rows between 2 result sets.

To understand these operators, let’s see some examples. We will use two different queries to extract data from our emp table and then we will perform UNION, MINUS and INTERSECT operations on these two sets of data.

UNION

SELECT * FROM EMPLOYEE WHERE ID = 5
UNION 
SELECT * FROM EMPLOYEE WHERE ID = 6
ID MGR_ID DEPT_ID NAME SAL DOJ
5 2 2.0 Anno 80.0 01-Feb-2012
6 2 2.0 Darl 80.0 11-Feb-2012

MINUS

SELECT * FROM EMPLOYEE
MINUS
SELECT * FROM EMPLOYEE WHERE ID > 2
ID MGR_ID DEPT_ID NAME SAL DOJ
1 2 Hash 100.0 01-Jan-2012
2 1 2 Robo 100.0 01-Jan-2012

INTERSECT

SELECT * FROM EMPLOYEE WHERE ID IN (2, 3, 5)
INTERSECT
SELECT * FROM EMPLOYEE WHERE ID IN (1, 2, 4, 5)
ID MGR_ID DEPT_ID NAME SAL DOJ
5 2 2 Anno 80.0 01-Feb-2012
2 1 2 Robo 100.0 01-Jan-2012

What is Self Join and why is it required?

Self Join is the act of joining one table with itself.

Self Join is often very useful to convert a hierarchical structure into a flat structure

In our employee table example above, we have kept the manager ID of each employee in the same row as that of the employee. This is an example of how a hierarchy (in this case employee-manager hierarchy) is stored in the RDBMS table. Now, suppose if we need to print out the names of the manager of each employee right beside the employee, we can use self join. See the example below:

SELECT e.name EMPLOYEE, m.name MANAGER
FROM EMPLOYEE e, EMPLOYEE m
WHERE e.mgr_id = m.id (+)
EMPLOYEE MANAGER
Pete Hash
Darl Hash
Inno Hash
Robo Hash
Tomiti Robo
Anno Robo
Privy Robo
Meme Pete
Bhuti Tomiti
Hash

The only reason we have performed a left outer join here (instead of INNER JOIN) is we have one employee in this table without a manager (employee ID = 1). If we perform inner join, this employee will not show-up.

How can we transpose a table using SQL (changing rows to column or vice-versa) ?

The usual way to do it in SQL is to use CASE statement or DECODE statement.

How to generate row number in SQL Without ROWNUM

Generating a row number – that is a running sequence of numbers for each row is not easy using plain SQL. In fact, the method  This method only works if there is at least one unique column in the table. This method will also work if there is no single unique column, but collection of columns that is unique. Anyway, here is the query:

 

SELECT name, sal, (SELECT COUNT(*) FROM EMPLOYEE i WHERE o.name >= i.name) row_num
FROM EMPLOYEE o
order by row_num


 

SALROW_NUM

801

602

803

1004

505

606

707

508

1009

7010

NAME
Anno
Bhuti Darl Hash Inno Meme Pete Privy Robo Tomiti

. For example, in Oracle database, every SQL result set contains a hidden column called ROWNUM. We can just explicitly select ROWNUM to get sequence numbers.

How to select first 5 records from a table?

In Oracle,

SELECT * 
FROM EMP
WHERE ROWNUM <= 5;

In SQL Server,

SELECT TOP 5 * FROM EMP;

Generic solution,

I believe a generic solution can be devised for this problem if and only if there exists at least one distinct column in the table. For example, in our EMP table ID is distinct. We can use that distinct column in the below way to come up with a generic solution of this question that does not require database specific functions such as ROWNUM, TOP etc.

SELECT  name 
FROM EMPLOYEE o
WHERE (SELECT count(*) FROM EMPLOYEE i WHERE i.name < o.name) < 5
name
Inno
Anno
Darl
Meme
Bhuti

I have taken “name” column in the above example since “name” is happened to be unique in this table. I could very well take ID column as well.

What is the difference between ROWNUM pseudo column and ROW_NUMBER() function?

ROWNUM is a pseudo column present in Oracle database returned result set prior to ORDER BY being evaluated. So ORDER BY ROWNUM does not work.

ROW_NUMBER() is an analytical function which is used in conjunction to OVER() clause wherein we can specify ORDER BY and also PARTITION BY columns.

Suppose if you want to generate the row numbers in the order of ascending employee salaries for example, ROWNUM will not work. But you may use ROW_NUMBER() OVER() like shown below:

SELECT name, sal, row_number() over(order by sal desc) rownum_by_sal
FROM EMPLOYEE o
name Sal ROWNUM_BY_SAL
Hash 100 1
Robo 100 2
Anno 80 3
Darl 80 4
Tomiti 70 5
Pete 70 6
Bhuti 60 7
Meme 60 8
Inno 50 9
Privy 50 10

What are the differences among ROWNUM, RANK and DENSE_RANK?

ROW_NUMBER assigns contiguous, unique numbers from 1.. N to a result set.

RANK does not assign unique numbers—nor does it assign contiguous numbers. If two records tie for second place, no record will be assigned the 3rd rank as no one came in third, according to RANK. See below:

SELECT name, sal, rank() over(order by sal desc) rank_by_sal
FROM EMPLOYEE o
name Sal RANK_BY_SAL
Hash 100 1
Robo 100 1
Anno 80 3
Darl 80 3
Tomiti 70 5
Pete 70 5
Bhuti 60 7
Meme 60 7
Inno 50 9
Privy 50 9

DENSE_RANK, like RANK, does not assign unique numbers, but it does assign contiguous numbers. Even though two records tied for second place, there is a third-place record. See below:

SELECT name, sal, dense_rank() over(order by sal desc) dense_rank_by_sal
FROM EMPLOYEE o
name Sal DENSE_RANK_BY_SAL
Hash 100 1
Robo 100 1
Anno 80 2
Darl 80 2
Tomiti 70 3
Pete 70 3
Bhuti 60 4
Meme 60 4
Inno 50 5
Privy 50 5

What does UNION do? What is the difference between UNION and UNION ALL?

UNION merges the contents of two structurally-compatible tables into a single combined table. The difference between UNION and UNION ALL is that UNION will omit duplicate records whereas UNION ALL will include duplicate records.

List and explain the different types of JOIN clauses supported in ANSI-standard SQL.

 

Consider the following two query results:

sql> select Count(*) as Total from Orders;
+-------+
| Total |
+-------+
|  100  |
+-------+

sql> select Count(*) as Cust123Total from Orders where customer_id = '123'
+--------------+
| Cust123Total |
+--------------+
|      15      |
+--------------+

Given the above query results, what will be the result of the query below?

sql> select Count(*) from Orders where customer_id <> '123'

Answering that the result will be 85 (i.e., 100 – 15) is not necessarily correct. Specifically, any records with a customer_id of NULL willnot be included in either count (i.e., they won’t be included in the count of records that do have a customer_id of 123, nor will they be included in the count of records that do not have a customer_id of 123).

What will be the result of the query below? Explain your answer and provide a version that behaves correctly.

select case when null = null then 'Yup' else 'Nope' end as Result;

This query will actually yield “Nope”, seeming to imply that null is not equal to itself! The reason for this is that the proper way to compare a value to null in SQL is with the is operator, not with =.

Accordingly, the correct version of the above query that yields the expected result (i.e., “Yup”) would be as follows:

select case when null is null then 'Yup' else 'Nope' end as Result;

Given the following tables:

sql> SELECT * FROM runners;
+----+--------------+
| id | name         |
+----+--------------+
|  1 | John Doe     |
|  2 | Jane Doe     |
|  3 | Alice Jones  |
|  4 | Bobby Louis  |
|  5 | Lisa Romero  |
+----+--------------+

sql> SELECT * FROM races;
+----+----------------+-----------+
| id | event          | winner_id |
+----+----------------+-----------+
|  1 | 100 meter dash |  2        |
|  2 | 500 meter dash |  3        |
|  3 | cross-country  |  2        |
|  4 | triathalon     |  NULL     |
+----+----------------+-----------+

What will be the result of the query below?

select * from runners where id not in (select winner_id from races)

Surprisingly, given the sample data provided, the result of this query will be an empty set. The reason for this is as follows: If the set being evaluated by the SQL NOT IN condition contains any values that are null, then the outer query here will return an empty set, even if there are many runner ids that match winner_ids in the races table.

Knowing this, a query that avoids this issue would be as follows:

select * from runners where id not in (select winner_id from races where winner_id is not null)

Given two tables created and populated as follows:

create table dbo.envelope(id int, user_id int)
create table dbo.docs(idnum int,pageseq int,doctext varchar(100))

Insert into dbo.envelope values(1,1),(2,2),(3,3)

insert into dbo.docs(idnum,pageseq) values(1,5),(2,6),(null,0)

What will the result be from the following query:

update docs set doctext=pageseq from docs inner join envelope on envelope.id=docs.idnum
where exists (select 1 from dbo.docs where id=envelope.id)

The result of the query will be as follows:

idnum	pageseq	doctext
1	5	5
2	6	6
NULL	0	NULL

The EXISTS clause in the above query is a red herring. It will always be true since ID is not a member of dbo.docs. As such, it will refer to the envelope table comparing itself to itself!

The idnum value of NULL will not be set since the join of NULL will not return a result when attempting a match with any value of envelope.

What is wrong with this SQL query? Correct it so it executes properly.

SELECT Id, YEAR(BillingDate) AS BillingYear 
FROM Invoices
WHERE BillingYear >= 2010;

The expression BillingYear in the WHERE clause is invalid. Even though it is defined as an alias in the SELECT phrase, which appears before the WHERE phrase, the logical processing order of the phrases of the statement is different from the written order. Most programmers are accustomed to code statements being processed generally top-to-bottom or left-to-right, but T-SQL processes phrases in a different order.

The correct query should be:

SELECT Id, YEAR(BillingDate) AS BillingYear
FROM Invoices
WHERE YEAR(BillingDate) >= 2010;

Given these contents of the Customers table:

Id	Name			ReferredBy
1	John Doe		NULL
2	Jane Smith		NULL
3	Anne Jenkins		2
4	Eric Branford		NULL
5	Pat Richards		1
6	Alice Barnes		2

Here is a query written to return the list of customers not referred by Jane Smith:

SELECT Name FROM Customers WHERE ReferredBy <> 2;

Although there are 4 customers not referred by Jane Smith (including Jane Smith herself), the query will only return one: Pat Richards. All the customers who were referred by nobody at all (and therefore have NULL in their ReferredBy column) don’t show up. But certainly those customers weren’t referred by Jane Smith, and certainly NULL is not equal to 2, so why didn’t they show up?

Anything compared to NULL evaluates to the third value in three-valued logic: UNKNOWN.

The query should be written:

SELECT Name FROM Customers WHERE ReferredBy IS NULL OR ReferredBy <> 2

Watch out for the following, though!

SELECT Name FROM Customers WHERE ReferredBy = NULL OR ReferredBy <> 2

This will return the same faulty set as the original. Why? We already covered that: Anything compared to NULL evaluates to the third value in the three-valued logic: UNKNOWN. That “anything” includes NULL itself! That’s why SQL Server provides the IS NULL and IS NOT NULL operators to specifically check for NULL. Those particular operators will always evaluate to true or false.

write a SQL query to return a list of all the invoices. For each invoice, show the Invoice ID, the billing date, the customer’s name, and the name of the customer who referred that customer (if any). The list should be ordered by billing date.

SELECT i.Id, i.BillingDate, c.Name, r.Name AS ReferredByName
FROM Invoices i
 JOIN Customers c ON i.CustomerId = c.Id
 LEFT JOIN Customers r ON c.ReferredBy = r.Id
ORDER BY i.BillingDate;

Assume a schema of Emp ( Id, Name, DeptId ) , Dept ( Id, Name).

If there are 10 records in the Emp table and 5 records in the Dept table, how many rows will be displayed in the result of the following SQL query:

Select * From Emp, Dept

The query will result in 50 rows as a “cartesian product” or “cross join”, which is the default whenever the ‘where’ clause is omitted.

Given a table SALARIES, such as the one below, that has m = male and f = femalevalues. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.

Id	Name Sex	Salary
1     A   m      2500
2     B   f      1500
3     C   m      5500
4     D   f       500
UPDATE SALARIES SET sex = CASE sex WHEN 'm' THEN 'f' ELSE 'm' END

 

Table Name : Employee
Employee_id First_name Last_name Salary Joining_date Department
1 John Abraham 1000000 01-JAN-13 12.00.00 AM Banking
2 Michael Clarke 800000 01-JAN-13 12.00.00 AM Insurance
3 Roy Thomas 700000 01-FEB-13 12.00.00 AM Banking
4 Tom Jose 600000 01-FEB-13 12.00.00 AM Insurance
5 Jerry Pinto 650000 01-FEB-13 12.00.00 AM Insurance
6 Philip Mathew 750000 01-JAN-13 12.00.00 AM Services
7 TestName1 123 650000 01-JAN-13 12.00.00 AM Services
8 TestName2 Lname% 600000 01-FEB-13 12.00.00 AM Insurance
Table Name : Incentives
Employee_ref_id Incentive_date Incentive_amount
1 01-FEB-13 5000
2 01-FEB-13 3000
3 01-FEB-13 4000
1 01-JAN-13 4500
2 01-JAN-13 3500

. Get all employee details from the employee table

 Select * from employee

. Get First_Name,Last_Name from employee table

 Select first_name, Last_Name from employee

. Get First_Name from employee table using alias name “Employee Name”

 Select first_name Employee Name from employee

. Get First_Name from employee table in upper case

 Select upper(FIRST_NAME) from EMPLOYEE

. Get First_Name from employee table in lower case

Select lower(FIRST_NAME) from EMPLOYEE

. Get unique DEPARTMENT from employee table

select distinct DEPARTMENT from EMPLOYEE

. Select first 3 characters of FIRST_NAME from EMPLOYEE

Oracle Equivalent of SQL Server SUBSTRING is SUBSTR,

Query : select substr(FIRST_NAME,0,3) from employee

SQL Server Equivalent of Oracle SUBSTR is SUBSTRING,

Query : select substring(FIRST_NAME,0,3) from employee

MySQL Server Equivalent of Oracle SUBSTR is SUBSTRING. In MySQL start position is 1, Query : select substring(FIRST_NAME,1,3) from employee

Get position of ‘o’ in name ‘John’ from employee table

Oracle Equivalent of SQL Server CHARINDEX is INSTR,

Query : Select instr(FIRST_NAME,’o’) from employee where first_name=’John’

SQL Server Equivalent of Oracle INSTR is CHARINDEX,

Query: Select CHARINDEX(‘o’,FIRST_NAME,0) from employee where first_name=’John’

MySQL Server Equivalent of Oracle INSTR is LOCATE,

Query: Select LOCATE(‘o’,FIRST_NAME) from employee where first_name=’John’

Get FIRST_NAME from employee table after removing white spaces from right side

select RTRIM(FIRST_NAME) from employee


. Get FIRST_NAME from employee table after removing white spaces from left side

select LTRIM(FIRST_NAME) from employee


. Get length of FIRST_NAME from employee table

Oracle,MYSQL Equivalent of SQL Server Len is Length ,

Query :select length(FIRST_NAME) from employee

SQL Server Equivalent of Oracle,MYSQL Length is Len,

Query :select len(FIRST_NAME) from employee


. Get First_Name from employee table after
replacing ‘o’ with ‘$’

select REPLACE(FIRST_NAME,'o','$') from employee


. Get First_Name and Last_Name as single column from employee table separated by a ‘_’

Oracle Equivalent of MySQL concat is ‘||’,

Query : Select FIRST_NAME|| ‘_’ ||LAST_NAME from EMPLOYEE

SQL Server Equivalent of MySQL concat is ‘+’, Query : Select FIRST_NAME + ‘_’ +LAST_NAME from EMPLOYEE

MySQL Equivalent of Oracle ‘||’ is concat, Query : Select concat(FIRST_NAME,’_’,LAST_NAME) from EMPLOYEE


. Get FIRST_NAME ,Joining year,Joining Month and Joining Date from employee table

SQL Queries in Oracle,

Select FIRST_NAME, to_char(joining_date,’YYYY’) JoinYear , to_char(joining_date,’Mon’), to_char(joining_date,’dd’) from EMPLOYEE

SQL Queries in SQL Server,

select SUBSTRING (convert(varchar,joining_date,103),7,4) , SUBSTRING (convert(varchar,joining_date,100),1,3) , SUBSTRING (convert(varchar,joining_date,100),5,2) from EMPLOYEE

SQL Queries in MySQL,

select year(joining_date),month(joining_date), DAY(joining_date) from EMPLOYEE

. Get all employee details from the employee table order by First_Name Ascending

Select * from employee order by FIRST_NAME asc


. Get all employee details from the employee table order by First_Name descending

Select * from employee order by FIRST_NAME desc

. Get all employee details from the employee table order by First_Name Ascending and Salary descending

Select * from employee order by FIRST_NAME asc,SALARY desc

. Get employee details from employee table whose employee name is “John”

Select * from EMPLOYEE where FIRST_NAME='John'


. Get employee details from employee table whose employee name are “John” and “Roy”

Select * from EMPLOYEE where FIRST_NAME in('John','Roy')


. Get employee details from employee table whose employee name are not “John” and “Roy”

Select * from EMPLOYEE where FIRST_NAME not in ('John','Roy')

. Get employee details from employee table whose first name starts with ‘J’

Select * from EMPLOYEE where FIRST_NAME like 'J%'


. Get employee details from employee table whose first name contains ‘o’

Select * from EMPLOYEE where FIRST_NAME like '%o%'


. Get employee details from employee table whose first name ends with ‘n’

Select * from EMPLOYEE where FIRST_NAME like '%n'

. Get employee details from employee table whose first name ends with ‘n’ and name contains 4 letters

Select * from EMPLOYEE where FIRST_NAME like '___n' (Underscores)


. Get employee details from employee table whose first name starts with ‘J’ and name contains 4 letters

Select * from EMPLOYEE where FIRST_NAME like 'J___' (Underscores)


. Get employee details from employee table whose Salary greater than 600000

Select * from EMPLOYEE where Salary >600000


. Get employee details from employee table whose Salary less than 800000

Select * from EMPLOYEE where Salary <800000


. Get employee details from employee table whose Salary between 500000 and 800000

Select * from EMPLOYEE where Salary between 500000 and 800000


. Get employee details from employee table whose name is ‘John’ and ‘Michael’

Select * from EMPLOYEE where FIRST_NAME in ('John','Michael')

. Get employee details from employee table whose joining year is “2013”

SQL Queries in Oracle, Select * from EMPLOYEE where to_char(joining_date,’YYYY’)=’2013′

SQL Queries in SQL Server, Select * from EMPLOYEE where SUBSTRING(convert(varchar,joining_date,103),7,4)=’2013′

SQL Queries in MySQL, Select * from EMPLOYEE where year(joining_date)=’2013′

. Get employee details from employee table whose joining month is “January”

SQL Queries in Oracle,

Select * from EMPLOYEE where to_char(joining_date,’MM’)=’01’ or Select * from EMPLOYEE where to_char(joining_date,’Mon’)=’Jan’

SQL Queries in SQL Server,

Select * from EMPLOYEE where SUBSTRING(convert(varchar,joining_date,100),1,3)=’Jan’

SQL Queries in MySQL,

Select * from EMPLOYEE where month(joining_date)=’01’

. Get employee details from employee table who joined before January 1st 2013

SQL Queries in Oracle,

Select * from EMPLOYEE where JOINING_DATE <to_date(’01/01/2013′,’dd/mm/yyyy’)

SQL Queries in SQL Server

(Format – “MM/DD/YYYY”), Select * from EMPLOYEE where joining_date <’01/01/2013′

SQL Queries in MySQL

(Format – “YYYY-DD-MM”), Select * from EMPLOYEE where joining_date <‘2013-01-01’


. Get employee details from employee table who joined after January 31st

SQL Queries in Oracle,

Select * from EMPLOYEE where JOINING_DATE >to_date(’31/01/2013′,’dd/mm/yyyy’)

SQL Queries in SQL Server and MySQL

(Format – “MM/DD/YYYY”), Select * from EMPLOYEE where joining_date >’01/31/2013′

SQL Queries in MySQL

(Format – “YYYY-DD-MM”), Select * from EMPLOYEE where joining_date >’2013-01-31′


. Get Joining Date and Time from employee table

SQL Queries in Oracle, select to_char(JOINING_DATE,’dd/mm/yyyy hh:mi:ss’) from EMPLOYEE

SQL Queries in SQL Server,

Select convert(varchar(19),joining_date,121) from EMPLOYEE

SQL Queries in MySQL,

Select CONVERT(DATE_FORMAT(joining_date,’%Y-%m-%d-%H:%i:00′),DATETIME) from EMPLOYEE


. Get Joining Date,Time including milliseconds from employee table

SQL Queries in Oracle,

select to_char(JOINING_DATE,’dd/mm/yyyy HH:mi:ss.ff’) from EMPLOYEE . Column Data Type should be “TimeStamp”

SQL Queries in SQL Server,

select convert(varchar,joining_date,121) from EMPLOYEE

SQL Queries in MySQL,

Select MICROSECOND(joining_date) from EMPLOYEE


. Get difference between JOINING_DATE and INCENTIVE_DATE from employee and incentives table

Select FIRST_NAME,INCENTIVE_DATE – JOINING_DATE from employee a inner join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID


. Get database date

SQL Queries in Oracle,

select sysdate from dual

SQL Queries in SQL Server,

select getdate()

SQL Query in MySQL,

select now()

. Get names of employees from employee table who has ‘%’ in Last_Name. Tip : Escape character for special characters in a query.

SQL Queries in Oracle,

Select FIRST_NAME from employee where Last_Name like ‘%?%%’

SQL Queries in SQL Server,

Select FIRST_NAME from employee where Last_Name like ‘%[%]%’

SQL Queries in MySQL,

Select FIRST_NAME from employee where Last_Name like ‘%\%%’

. Get Last Name from employee table after replacing special character with white space

SQL Queries in Oracle,

Select translate(LAST_NAME,’%’,’ ‘) from employee

SQL Queries in SQL Server and MySQL,

Select REPLACE(LAST_NAME,’%’,’ ‘) from employee

. Get department,total salary with respect to a department from employee table.

Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by department


. Get department,total salary with respect to a department from employee table order by total salary descending

Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by DEPARTMENT order by Total_Salary descending

. Get department,no of employees in a department,total salary with respect to a department from employee table order by total salary descending

Select DEPARTMENT,count(FIRST_NAME),sum(SALARY) Total_Salary from employee group by DEPARTMENT order by Total_Salary descending


. Get department wise average salary from employee table order by salary ascending

select DEPARTMENT,avg(SALARY) AvgSalary from employee group by DEPARTMENT order by AvgSalary asc


. Get department wise maximum salary from employee table order by salary ascending

select DEPARTMENT,max(SALARY) MaxSalary from employee group by DEPARTMENT order by MaxSalary asc


. Get department wise minimum salary from employee table order by salary ascending

select DEPARTMENT,min(SALARY) MinSalary from employee group by DEPARTMENT order by MinSalary asc


. Select no of employees joined with respect to year and month from employee table

SQL Queries in Oracle,

select to_char (JOINING_DATE,’YYYY’) Join_Year,to_char (JOINING_DATE,’MM’) Join_Month,count(*) Total_Emp from employee group by to_char (JOINING_DATE,’YYYY’),to_char(JOINING_DATE,’MM’)

SQL Queries in SQL Server,

select datepart (YYYY,JOINING_DATE) Join_Year,datepart (MM,JOINING_DATE) Join_Month,count(*) Total_Emp from employee group by datepart(YYYY,JOINING_DATE), datepart(MM,JOINING_DATE)

SQL Queries in MySQL,

select year (JOINING_DATE) Join_Year,month (JOINING_DATE) Join_Month,count(*) Total_Emp from employee group by year(JOINING_DATE), month(JOINING_DATE)


. Select department,total salary with respect to a department from employee table where total salary greater than 800000 order by Total_Salary descending

Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by DEPARTMENT having sum(SALARY) >800000 order by Total_Salary desc

. Select employee details from employee table if data exists in incentive table ?

select * from EMPLOYEE where exists (select * from INCENTIVES)

Explanation : Here “exists” statement helps us to do the job of If statement. Main query will get executed if the sub query returns at least one row. So we can consider the sub query as “If condition” and the main query as “code block” inside the If condition. We can use any SQL commands (Joins, Group By , having etc) in sub query. This command will be useful in queries which need to detect an event and do some activity.

. How to fetch data that are common in two query results ?

select * from EMPLOYEE where EMPLOYEE_ID INTERSECT select * from EMPLOYEE where EMPLOYEE_ID < 4

 

Explanation : Here “INTERSECT” command is used to fetch data that are common in 2 queries. In this example, we had taken EMPLOYEE table in both the queries.We can apply INTERSECT command on different tables. The result of the above query will return employee details of “ROY” because, employee id of ROY is 3, and both query results have the information about ROY.

. Get Employee ID’s of those employees who didn’t receive incentives without using sub query ?

select EMPLOYEE_ID from EMPLOYEE
MINUS
select EMPLOYEE_REF_ID from INCENTIVES

Explanation : To filter out certain information we use MINUS command. What MINUS Command odes is that, it returns all the results from the first query, that are not part of the second query. In our example, first three employees received the incentives. So query will return employee id’s 4 to 8.

 

. Select 20 % of salary from John , 10% of Salary for Roy and for other 15 % of salary from employee table

SELECT FIRST_NAME, CASE FIRST_NAME WHEN ‘John’ THEN SALARY * .2 WHEN ‘Roy’ THEN SALARY * .10 ELSE SALARY * .15 END “Deduced_Amount” FROM EMPLOYEE

 

Explanation : Here, we are using “SQL CASE” statement to achieve the desired results. After case statement, we had to specify the column on which filtering is applied. In our case it is “FIRST_NAME”. And in then condition, specify the name of filter like John, Roy etc. To handle conditions outside our filter, use else block where every one other than John and Roy enters.

. Select Banking as ‘Bank Dept’, Insurance as ‘Insurance Dept’ and Services as ‘Services Dept’ from employee table

SQL Queries in Oracle,

SELECT distinct DECODE (DEPARTMENT, ‘Banking’, ‘Bank Dept’, ‘Insurance’, ‘Insurance Dept’, ‘Services’, ‘Services Dept’) FROM EMPLOYEE

SQL Queries in SQL Server and MySQL,

SELECT case DEPARTMENT when ‘Banking’ then ‘Bank Dept’ when ‘Insurance’ then ‘Insurance Dept’ when ‘Services’ then ‘Services Dept’ end FROM EMPLOYEE

 

Explanation : Here “DECODE” keyword is used to specify the alias name. In oracle we had specify, Column Name followed by Actual Name and Alias Name as arguments. In SQL Server and MySQL, we can use the earlier switch case statements for alias names.

. Delete employee data from employee table who got incentives in incentive table

delete from EMPLOYEE where EMPLOYEE_ID in (select EMPLOYEE_REF_ID from INCENTIVES)

 

Explanation : Trick about this question is that we can’t delete data from a table based on some condition in another table by joining them. Here to delete multiple entries from EMPLOYEE table, we need to use Subquery. Entries will get deleted based on the result of Subquery.

. Insert into employee table Last Name with ” ‘ ” (Single Quote – Special Character)

Tip - Use another single quote before special character
Insert into employee (LAST_NAME) values ('Test''')

. Select Last Name from employee table which contain only numbers

Select * from EMPLOYEE where lower(LAST_NAME)=upper(LAST_NAME)

Explanation : In order to achieve the desired result, we use “ASCII” property of the database. If we get results for a column using Lower and Upper commands, ASCII of both results will be same for numbers. If there is any alphabets in the column, results will differ.

. Write a query to rank employees based on their incentives for a month

select FIRST_NAME,INCENTIVE_AMOUNT,DENSE_RANK() OVER (PARTITION BY INCENTIVE_DATE ORDER BY INCENTIVE_AMOUNT DESC) AS Rank from EMPLOYEE a, INCENTIVES b where a.EMPLOYEE_ID=b.EMPLOYEE_REF_ID

 

Explanation : In order to rank employees based on their rank for a month, “DENSE_RANK” keyword is used. Here partition by keyword helps us to sort the column with which filtering is done. Rank is provided to the column specified in the order by statement. The above query ranks employees with respect to their incentives for a given month.

. Update incentive table where employee name is ‘John’

update INCENTIVES set INCENTIVE_AMOUNT=’9000′ where EMPLOYEE_REF_ID=(select EMPLOYEE_ID from EMPLOYEE where FIRST_NAME=’John’ )

 

Explanation : We need to join Employee and Incentive Table for updating the incentive amount. But for update statement joining query wont work. We need to use sub query to update the data in the incentive table. 

. Select first_name, incentive amount from employee and incentives table for those employees who have incentives

Select FIRST_NAME,INCENTIVE_AMOUNT from employee a inner join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

. Select first_name, incentive amount from employee and incentives table for those employees who have incentives and incentive amount greater than 3000

Select FIRST_NAME,INCENTIVE_AMOUNT from employee a inner join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID and INCENTIVE_AMOUNT >3000

. Select first_name, incentive amount from employee and incentives table for all employes even if they didn’t get incentives

Select FIRST_NAME,INCENTIVE_AMOUNT from employee a left join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

. Select first_name, incentive amount from employee and incentives table for all employees even if they didn’t get incentives and set incentive amount as 0 for those employees who didn’t get incentives.

SQL Queries in Oracle,

Select FIRST_NAME,nvl(INCENTIVE_AMOUNT,0) from employee a left join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

SQL Queries in SQL Server,

Select FIRST_NAME, ISNULL(INCENTIVE_AMOUNT,0) from employee a left join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

SQL Queries in MySQL,

Select FIRST_NAME, IFNULL(INCENTIVE_AMOUNT,0) from employee a left join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

. Select first_name, incentive amount from employee and incentives table for all employees who got incentives using left join

SQL Queries in Oracle,

Select FIRST_NAME,nvl(INCENTIVE_AMOUNT,0) from employee a right join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

SQL Queries in SQL Server,

Select FIRST_NAME, isnull(INCENTIVE_AMOUNT,0) from employee a right join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

SQL Queries in MySQL,

Select FIRST_NAME, IFNULL(INCENTIVE_AMOUNT,0) from employee a right join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

. Select max incentive with respect to employee from employee and incentives table using sub query

SQL Queries in Oracle,

select DEPARTMENT,(select nvl(max(INCENTIVE_AMOUNT),0) from INCENTIVES where EMPLOYEE_REF_ID=EMPLOYEE_ID) Max_incentive from EMPLOYEE

SQL Queries in SQL Server,

select DEPARTMENT,(select ISNULL(max(INCENTIVE_AMOUNT),0) from INCENTIVES where EMPLOYEE_REF_ID=EMPLOYEE_ID) Max_incentive from EMPLOYEE

SQL Queries in SQL Server,

select DEPARTMENT,(select IFNULL (max(INCENTIVE_AMOUNT),0) from INCENTIVES where EMPLOYEE_REF_ID=EMPLOYEE_ID) Max_incentive from EMPLOYEE

. Select TOP 2 salary from employee table

SQL Queries in Oracle,

select * from (select * from employee order by SALARY desc) where rownum <3

SQL Queries in SQL Server,

select top 2 * from employee order by salary desc

SQL Queries in MySQL, select * from employee order by salary desc limit 2

. Select TOP N salary from employee table

SQL Queries in Oracle,

select * from (select * from employee order by SALARY desc) where rownum <N + 1

SQL Queries in SQL Server,

select top N * from employee

SQL Queries in MySQL,

select * from employee order by salary desc limit N

. Select 2nd Highest salary from employee table

SQL Queries in Oracle,

select min(salary) from (select * from (select * from employee order by SALARY desc) where rownum <3)

SQL Queries in SQL Server,

select min(SALARY) from (select top 2 * from employee) a

SQL Queries in MySQL,

select min(SALARY) from (select * from employee order by salary desc limit 2) a

. Select Nth Highest salary from employee table

SQL Queries in Oracle,

select min(salary) from (select * from (select * from employee order by SALARY desc) where rownum <N + 1)

SQL Queries in SQL Server,

select min(SALARY) from (select top N * from employee) a

SQL Queries in MySQL,

select min(SALARY) from (select * from employee order by salary desc limit N) a

. Select First_Name,LAST_NAME from employee table as separate rows

select FIRST_NAME from EMPLOYEE union select LAST_NAME from EMPLOYEE

 

 

. Write syntax to delete table employee

 

DROP table employee;

. Write syntax to set EMPLOYEE_ID as primary key in employee table

ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY KEY(EMPLOYEE_ID)

. Write syntax to set 2 fields(EMPLOYEE_ID,FIRST_NAME) as primary key in employee table

ALTER TABLE EMPLOYEE add CONSTRAINT EMPLOYEE_PK PRIMARY KEY(EMPLOYEE_ID,FIRST_NAME)

. Write syntax to drop primary key on employee table

Alter TABLE EMPLOYEE drop CONSTRAINT EMPLOYEE_PK;

. Write Sql Syntax to create EMPLOYEE_REF_ID in INCENTIVES table as foreign key with respect to EMPLOYEE_ID in employee table

ALTER TABLE INCENTIVES ADD CONSTRAINT INCENTIVES_FK FOREIGN KEY (EMPLOYEE_REF_ID) REFERENCES EMPLOYEE(EMPLOYEE_ID)

. Write SQL to drop foreign key on employee table

ALTER TABLE INCENTIVES drop CONSTRAINT INCENTIVES_FK;

. Write SQL to create Orcale Sequence

CREATE SEQUENCE EMPLOYEE_ID_SEQ START WITH 0 NOMAXVALUE MINVALUE 0 NOCYCLE NOCACHE NOORDER;