Representing 'not in' subquery as join - sql

I am trying to convert the following query:
select *
from employees
where emp_id not in (select distinct emp_id from managers);
into a form where I represent the subquery as a join. I tried doing:
select *
from employees a, (select distinct emp_id from managers) b
where a.emp_id!=b.emp_id;
I also tried:
select *
from employees a, (select distinct emp_id from managers) b
where a.emp_id not in b.emp_id;
But it does not give the same result. I have tried the 'INNER JOIN' syntax as well, but to no avail. I have become frustrated with this seemingly simple problem. Any help would be appreciated.

Assume employee Data set of
Emp_ID
1
2
3
4
5
6
7
Assume Manger data set of
Emp_ID
1
2
3
4
5
8
9
select *
from employees
where emp_id not in (select distinct emp_id from managers);
The above isn't joining tables so no Cartesian product is generated... you just have 7 records you're looking at...
The above would result in 6 and 7 Why? only 6 and 7 from Employee Data isn't in the managers table. 8,9 in managers is ignored as you're only returning data from employee.
select *
from employees a, (select distinct emp_id from managers) b
where a.emp_id!=b.emp_id;
The above didnt' work because a Cartesian product is generated... All of Employee to all of Manager (assuming 7 records in each table 7*7=49)
so instead of just evaluating the employee data like you were in the first query. Now you also evaluate all managers to all employees
so Select * results in
1,1
1,2
1,3
1,4
1,5
1,8
1,9
2,1
2,2...
Less the where clause matches...
so 7*7-7 or 42. and while this may be the answer to the life universe and everything in it, it's not what you wanted.
I also tried:
select *
from employees a, (select distinct emp_id from managers) b
where a.emp_id not in b.emp_id;
Again a Cartesian... All of Employee to ALL OF Managers
So this is why a left join works
SELECT e.*
FROM employees e
LEFT OUTER JOIN managers m
on e.emp_id = m.emp_id
WHERE m.emp_id is null
This says join on ID first... so don't generate a Cartesian but actually join on a value to limit the results. but since it's a LEFT join return EVERYTHING from the LEFT table (employee) and only those that match from manager.
so in our example would be returned as e.emp_Di = m.Emp_ID
1,1
2,2
3,3
4,4
5,5
6,NULL
7,NULL
now the where clause so
6,Null
7,NULL are retained...
older ansii SQL standards for left joins would have been *= in the where clause...
select *
from employees a, managers b
where a.emp_id *= b.emp_id --I never remember if the * is the LEFT so it may be =*
and b.emp_ID is null;
But I find this notation harder to read as the join can get mixed in with the other limiting criteria...

Try this:
select e.*
from employees e
left join managers m on e.emp_id = m.emp_id
where m.emp_id is null
This will join the two tables. Then we discard all rows where we found a matching manager and are left with employees who aren't managers.

Your best bet would probably be a left join:
select
e.*
from employees e
left join managers m on e.emp_id = m.emp_id
where
m.emp_id is null;
The idea here is you're saying that you want to select everything from employees, including anything that matches in the manager table based on emp_id and then filtering out the rows that actually have something in the manager table.

Use Left Outer Join instead
select e.*
from employees e
left outer join managers m
on e.emp_id = m.emp_id
where m.emp_id is null
left outer join will preserve the rows from m table even if they do not have a match i e table based on the emp_id field. The we filter on where m.emp_id is null - give me all the rows from e where there's no matching record in m table.
A bit more on the subject can be found here:
Visual representation of joins
from employees a, (select distinct emp_id from managers) b implies cross join - all posible combinations between tables (and you needed left outer join instead)

The MINUS keyword should do the trick:
SELECT e.* FROM employees e
MINUS
Select m.* FROM managers m
Hope that helps...

select *
from employees
where Not (emp_id in (select distinct emp_id from managers));

Related

INNER JOIN and Count POSTGRESQL

I am learning postgresql and Inner join I have following table.
Employee
Id Name DepartmentId
1 John S. 1
2 Smith P. 1
3 Anil K. 2
Department
Department
Id Name
1 HR
2 Admin
I want to query to return the Department Name and numbers of employee in each department.
SELECT Department.name , COUNT(Employee.id) FROM Department INNER JOIN Employee ON Department.Id = Employee.DepartmentId Group BY Employee.department_id;
I dont know what I did wrong as I am new to database Query.
When involving all rows or major parts of the "many" table, it's typically faster to aggregate first and join later. Certainly the case here, since we are after counts for "each department", and there is no WHERE clause at all.
SELECT d.name, COALESCE(e.ct, 0) AS nr_employees
FROM department d
LEFT JOIN (
SELECT department_id AS id, count(*) AS ct
FROM employee
GROUP BY department_id
) e USING (id);
Also made it a LEFT [OUTER] JOIN, to keep departments without any employees in the result. And COALESCE to report 0 employees instead of NULL in that case.
Related, with more explanation:
Query with LEFT JOIN not returning rows for count of 0
Your original query would work too, after fixing the GROUP BY clause:
SELECT department.name, COUNT(employee.id)
FROM department
INNER JOIN employee ON department.id = employee.department_id
Group BY department.id; --!
That's assuming department.id is the PRIMARY KEY of the table, in which case it covers all columns of that table, including department.name. And you may want LEFT JOIN like above.
Aside: Consider legal, lower-case names exclusively in Postgres. See:
Are PostgreSQL column names case-sensitive?

subquery and join not giving the same result

1
select *
from employees
where salary > (select max(salary) from employees where department_id=50)
2
select *
from employees e left join
employees d
on e.DEPARTMENT_ID =d.DEPARTMENT_ID
where d.salary > (select max(salary) from employees where department_id=50)
why the second query is giving multiple record
i want achieve the same result as of 1st query using join.....
Thanks in Advance......
Rocky, the first select is correct. Why do you want to do any join? Without further information the objective of the second select is not clear (nonsense).
I can't see the point about joining against the same table by DEPARTMENT_ID. Anyway, the problem about duplicates is because you are joining the same two tables by a key is not pk, basically you are multiplyng each employee for all the employees of the same department. This version eliminate duplicates but still has no improvement from the first one.
select *
from employees e left join
employees d
on e.employee_ID = d.employee_ID
where d.salary > (select max(salary) from employees where department_id=50)
You are probably looking for an anti join. This is a pattern mainly used in a young DBMS where IN and EXISTS clauses are slow compared to joins, because the developers focused on joins only.
You are looking for all employees whose salaries are greater than all salaries in department 50. With other words: WHERE NOT EXISTS a salary greater or equal in department 50.
Your query can hence be written as:
select *
from employees e
where not exists
(
select null
from employees e50
where e50.department_id = 50
and e50.salary >= e.salary
);
As an anti join (an outer join where you dismiss all matches):
select *
from employees e
left join employees e50 on e50.department_id = 50 and e50.salary >= e.salary
where e50.salary is null;

Combining two Oracle SQL queries into one

I need to combine 2 query conditions in one SQL statement. I am unable to logically combine them.
1) Employee whose leave is approved by manager
select e.employee_name,r.request_from_Date,r.request_to_Date from employee_leave e,emp_leave_request r
where e.employee_id=r.request_from_id and e.employee_manager_id= r.request_to_id
and r.request_Approved_date is not null
and r.request_reject_Date is null
and r.request_cancelled_Date is null;
2) Employee who is part of manager's team
select employee_id, employee_name, employee_email, employee_username, employee_leave_normal, employee_contact_no,employee_designation
from employee_leave a
where exists(select 1 from employee_leave b where lower(b.employee_username)=lower(:APP_USER) and a.employee_manager_id=b.employee_id);
You can use INNER JOIN to achieve the same.Please learn what is an INNER join here
SELECT e1.*,
e.request_from_date,
e.request_to_date
FROM (
SELECT e.employee_id,
e.employee_name,
r.request_from_date,
r.request_to_date
FROM employee_leave e,
emp_leave_request r
WHERE e.employee_id=r.request_from_id
AND e.employee_manager_id= r.request_to_id
AND r.request_approved_date IS NOT NULL
AND r.request_reject_date IS NULL
AND r.request_cancelled_date IS NULL)e
inner join
(
SELECT employee_id,
employee_name,
employee_email,
employee_username,
employee_leave_normal,
employee_contact_no,
employee_designation
FROM employee_leave a
WHERE EXISTS
(
SELECT 1
FROM employee_leave b
WHERE Lower(b.employee_username)=Lower(:APP_USER)
AND a.employee_manager_id=b.employee_id) e1
ON e.employee_id=e1.employee_id
Use union to combine 2 sql select queries
example:
https://www.w3schools.com/sql/sql_union.asp

How to combine two columns from different tables that have a similar name but have different values in SQL Server

I have three tables (example) STAFF, STU, EMP.
I want to combine the column EMPID in table STAFF and table EMP into 1 column?
My previous query is like this,
SELECT *
FROM STU s
FULL OUTER JOIN STAFF st ON st.STAFFID = STUID
FULL OUTER JOIN EMP e ON s.STUID = st.EMPID
The result is like this
The expected result is just like the above screenshot, but I want to join EMPID into one column only.
UPDATE:
I tried using this query:
SELECT
stu.stuid, stu.stuname, stu.stucode,
s.staffid, s.staffname, s.staffcode,
emp.empname, emp.empcode,
COALESCE (emp.empid, staff.staffid) AS col
FROM
STU, Staff, EMP
FULL OUTER JOIN
STAFF s ON s.STAFFID = stu.STUID
FULL OUTER JOIN
EMP e ON stu.STUID = s.EMPID
but it displays an error like this
Use below query to get the desired result.
SELECT s.StuID, s.StuName, s.Stucode, st.StaffId, st.StaffName, st.Staffcode, isnull(st.EmpId, e.EmpId) EmpId, e.EmpCode, e.EmpName
FROM STU s FULL outer JOIN
STAFF st
ON st.STAFFID = STUID FULL OUTER JOIN
EMP e
ON s.STUID = st.EMPID
Note: You will get the one emp Id column as needed. If Staff emp id is not null then staff emp id will be displayed else employee emp id will be displayed

SQL query returns student id, course section id, and grade when section id 1000

Using Oracle Apex Browser, image of database
http://imgur.com/a/Hhblp#0
select s_ID, c_sec_ID, grade
from s_ID.ID, c_sec_ID.csID, grade.ID, grade.csID
where c_sec_ID = 1000
^ All I think of and I'm not sure if I'm suppose to join them together or group them either.
You have to join these tree tables COURSE_SECTION, ENROLLMENT and STUDENT to get desired output. Put INNER JOIN on three tables and add
Where Clause to filter records.
You can try this
SELECT S.s_ID, C.c_sec_ID, E.grade
FROM COURSE_SECTION C INNER JOIN ENROLLMENT E ON C.C_SEC_ID = E.C_SEC_ID
INNER JOIN STUDENT S ON S.S_ID = E.S_ID
WHERE C.C_SEC_ID = 1000