DataStage1
DataStage1
sql
Copy code
SELECT *
FROM (
FROM your_table
) subquery
WHERE rn % 2 = 1;
sql
Copy code
SELECT *
FROM (
FROM your_table
) subquery
WHERE rn % 2 = 0;
Q) . Write a SQL Query to find Max salary and Department name from
each department?
FROM Employees
GROUP BY DepartmentName;
Q) Query to find records in Table A not in Table B without using NOT IN.
If the structure of tableA and tableB is same then we can use ‘*’
But if structure of the table are same then we can minus operator on the
basis of ID column.
Employee table:
ID NAME EMAIL
10 John jbaldwin
20 George gadams
30 John jsmith
Answer: This is a simple question with one trick. The trick here is to
use Group by on two columns Name and Email.
FROM Employee
HAVING
COUNT(*) > 1
Q. Write a SQL Query to find Max salary from each department.
10, 1000, 2
20, 5000, 3
30, 3000, 2
Answer:
We can first use group by DeptID on Employee table and then get the Max
salary from each Dept group.
FROM Employee
GROUP BY DeptID
Q. Write SQL query to get the nth highest salary among all
Employees.
ID, Salary
10, 2000
11, 5000
12, 3000
Answer:
SELECT *
WHERE (N-1) = (
SELECT COUNT(DISTINCT(emp2.salary))
SELECT * FROM (
SELECT emp.*,
WHERE rnum = n;
Answer:
In Oracle we can use Top to limit the number of records. We can also use
Rownum < 11 to get the only 10 or less number of records.
This SQL query appears a bit tricky. We can use BETWEEN clause to get all
the employees whose date of birth lies between two given dates.
SELECT EmpName
FROM Employees
Answer: We can use to_char function with ‘Q’ option for quarter to get
quarter from a date.
AS quarter
FROM DUAL
Q. Write Query to find employees with duplicate email.
Employee table:
ID NAME EMAIL
10 John jsmith
20 George gadams
30 Jane jsmith
FROM Employee
GROUP BY email
Answer:
We can use UPPER function for comparing the both sides with uppercase.
SELECT *
FROM Employees
ROWID is the physical location of a row. We can do very fast lookup based
on ROWID. In a transaction where we first search a few rows and then
update them one by one, we can use ROWID.
But ROWID of a record can change over time. If we rebuild a table a record
can get a new ROWID.
We can also use DECODE function in Oracle SQL for writing simple If/Else
logic.
DDL vs. DML: DDL statements are used for creating and defining
the Database structure. DML statements are used for managing
data within Database.
Triggers: After DDL statements no triggers are fired. But after DML
statements relevant triggers can be fired.
In SQL, there are certain special characters and words that are reserved
for special purpose. E.g. & is a reserved character.
When we want to use these special characters in the context of our data,
we have to use Escape characters to pass the message to database to
interpret these as non Special / non Reserved characters.
Main differences between Primary key and Unique key in SQL are:
Null value: In some DBMS Primary key cannot be NULL. E.g. MySQL
adds NOT NULL to Primary key. A Unique key can have null values.
x | y
- - -|- -
10 | 30
20 | 40
30 | 50
40 | 60
In above tables (10,20) are unique to table X, (30,40) are common, and
(50,60) are unique to table Y.
INNER JOIN
An INNER JOIN by using following query will give the intersection of the
two tables X and Y. The intersection is the common data between these
tables.
x |y
--- +--
30 | 30
40 | 40
OUTER JOIN
A full OUTER JOIN by using following query will us the union of X and Y. It
will have all the rows in X and all the rows in Y. If some row in X has not
corresponding value in Y, then Y side will be null, and vice versa.
x | y
----- + -----
10 | null
20 | null
30 | 30
40 | 40
null | 60
null | 50
E.g.
x | y
- - -|- -
10 | 30
20 | 40
30 | 50
40 | 60
In above tables (10,20) are unique to table X, (30,40) are common, and
(50,60) are unique to table Y.
A left OUTER JOIN by using following query will give us all rows in X and
common rows in X and Y.
x | y
-- -+-----
10 | null
20 | null
30 | 30
40 | 40
A right OUTER JOIN by using following query will give all rows in Y and
common rows in X and Y.
select * from X RIGHT OUTER JOIN Y on X.x = Y.y;
x | y
----- +----
30 | 30
40 | 40
null | 50
null | 60
FROM Employee
E.g. We can group by department and only select departments that have
more than 10 employees.
FROM Employee
Low cardinality: Low cardinality columns are the columns with few
unique values. Typically status, Boolean flags, types, gender etc. are
Low-cardinality columns.
Many students have common last names. Some students have unique last
names. The values for these column are spread out evenly. Therefore it is
Normal Cardinality column.
Since there are only three possible values stored in this column, it is a Low
cardinality column.
MERGE
WHEN MATCHED
THEN
UPDATE
THEN
Main difference between UNION and UNION ALL is that UNION removes
duplicate records, but UNION ALL does not remove duplicate records.
A B
10 15
20 20
Employee
ID | Emp_name
1 | Jane
2 | George
3 | John
Department
ID | Dept_name | Emp_id
1 | Marketing | 1
2 | Finance | 2
3 | Technology | null
SELECT *
FROM Employee
FROM Department)
Answer: The above query will return no records. The reason for this is
presence of null value in Emp_id column of Department table.
SELECT *
FROM Employee
FROM Order
Answer:
FROM Order
SELECT Name
FROM Employee
Employee Table:
Id Name DeptID
1 John NULL
2 George 2
3 Smith 1
4 Ray NULL
Answer:
There are 3 Employees (John, George and Ray) not in Dept 1. But Query
returns only one result: George.
Since we are just looking for employees not in Dept 1, query does not
compare DeptID with NULL. So Employees without a department are not
returned.
SELECT Name
FROM Employee
OR DeptID <> 1;
Based on the steps in Execution plan, we can alter the plan to include or
exclude some steps or use some index etc. This helps in Query tuning and
Query optimization for SQL queries.
For a table with N records and another table with M records. Cartesian
Product has N * M number of records.
Employee
Id Name DeptId
1 John 1
2 George 2
3 Jane 1
4 Smith 2
Answer:
CASE DeptId
1 | John |3 | 10
2 | Smith |3 | 10
3 | Jane |4 | 20
Answer: We can use WITH clause and SELF JOIN to get the required data.
By WITH clause we get the count of employees in each department. Then
we use SELF JOIN to get name of Manager because manager is also an
employee.
WITH d_count AS (
FROM employee
GROUP BY deptno)
m.name AS Manager_name
dc.d_count AS Dept_count
FROM employee e,
d_count dc,
employee m
Let say in a given table Test_table if column_1 and column_2 of two rows
are same, then these rows are considered equal.
We can use GROUP BY clause to group the rows with columns that are
used for checking equality. Any group that have more than 1 rows will
have duplicate rows.
FROM Test_table
Let say in a given table Test_table if column_1 and column_2 of two rows
are same, then these rows are considered equal.
In Oracle we can use rowid of two rows to find that these rows are
different.
DELETE FROM
Test_table a
WHERE
a.rowid >
ANY (
SELECT
b.rowid
FROM
Test_table b
WHERE
a.column_1 = b.column_1
AND
a.column_2 = b.column_2
);
We use NVL and NVL2 functions to check if a value is NULL or not. Both
these functions can be replaced with DECODE or CASE statements.
Both RANK and DENSE_RANK functions are used to get the ranking of an
ordered partition.
In a tie, RANK function skips the next ranking(s) and assigns same rank to
values that tie. So there will be gaps in the rank.
In a tie, DENSE_RANK function does not skip the ranks. It assigns same
rank to values that tie. But next rank will be consecutive rank.
E.g. In set (10, 10, 20, 30, 30, 40), RANK returns (1,1,3,4,4,6)
In SQL, WITH clause is used to create a Subquery or View for a set of data.
Reduce Repetition: WITH clause can create a subset of data that can
be reused multiple times in the main query.
E.g. In following query we use WITH clause to get the set of employee in
Finance department. Then we use this subset fin_employee to filter based
on AGE less than 30 and Female Gender.
We have used the same set fin_employee multiple times in main query.
WITH fin_employee AS
(SELECT *
FROM Employee
SELECT *
FROM fin_employee
UNION ALL
SELECT *
FROM fin_employee
In second case, we can use a CURSOR to view the whole data set in a
sequence.
ID | Name | Grade
1 | George |1
2 | Smith |2
Answer: We can use WITH clause for this problem. We first get the
number students in each grade by using GROUP BY on grade. Then we use
Sub-Query returned by WITH clause in Main query.
WITH grade_count AS (
FROM student
GROUP BY grade)
gc.grade_count AS grade_count
FROM student s,
grade_count gc
Q. Write SQL Query to get the list of grades with total score
more than average score.
Answer: We can use WITH clause to get the total score in each grade. We
can also use WITH clause to get the average score among all grades. Then
we can use the two sub-queries to get the list of GRADES with Score total
more than average score.
WITH
grade_score AS (
GROUP BY grade_num),
avg_score AS (
FROM grade_score)
SELECT *
FROM grade_score
ORDER BY grade_num;
We can use GROUP BY for this purpose. It can print the distinct groups of
PRODUCT NAME.
SELECT prod_name
FROM product
GROUP BY prod_name
ZIPCODE
7500
7525
7550
7600
7575
We can use self join to find the list of Zipcodes that are smaller than at
least one other Zipcode. Once we get that list, we just use NOT IN to find
the Zipcode from Zipcode_list that does not exist in this smaller list. That
will be the maximum Zipcode with no Zipcode bigger than it.
FROM Zipcode_list
SELECT Smaller_list.Zipcode
Students
Grade | Name
1 | John
1 | George
1 | Jane
2 | Smith
2 | Anne
2 | Scott
3 | Larry
3 | Bill
Answer:
We can use LISTAGG function in Oracle for this purpose. It can transpose
rows to column type values. We can set the delimiter as comma in
LISTAGG function. And then we can group the students by using Grade in
GROUP BY clause.
FROM student
GROUP BY grade;
Grade Students
---------- --------------------------------------------------
1 John,George,Jane
2 Smith,Anne,Scott
3 Larry,Bill
When we write a subquery in such a way that inner subquery and outer
main query are interdependent, then we call it s correlated Sub query. In
this case, for executing every row of inner query, the outer query is also
executed. The inner query needs data from the outer query for its
execution.
E.g.
SELECT e.emp_name
FROM employee e
FROM dept d
The starting point will be the employee who does not have a manager.
Below that we can connect the employee IDs with their Manager IDs and
keep printing the records.
Oracle provides a pseudocolumn LEVEL that gives the level of each record
in hierarchy.
FROM Employee
John 10 1
George 14 10 2
Jill 16 14 3
Bill 15 14 3
Jay 18 14 3
Q. Views
Types of Views
1. Simple View:
Example:
sql
2. Complex View:
Example:
sql
FROM Employees
GROUP BY Department;