Oracle: select from two tables - oracle10g

I have two tables EMPLOYEE and DEPARTMENT.
Columns of the DEPARTMENT table:
DEPARTMENT_ID
DEPARTMENT_NAME
MANAGER_ID
LOCATION_ID
Columns of EMPLOYEE table
EMPLOYEE_ID
FIRST_NAME
LAST_NAME
EMAIL
PHONE_NUMBER
HIRE_DATE DATE
JOB_ID
SALARY
COMMISSION_PCT
MANAGER_ID
DEPARTMENT_ID
When the desired number appears DEPARTMENT_ID chose EMPLOYEE_ID
FIRST_NAME
LAST_NAME
EMAIL
PHONE_NUMBER
HIRE_DATE DATE
JOB_ID
SALARY
COMMISSION_PCT
MANAGER_ID
DEPARTMENT_ID

Please execute this query
select
emp.first_name, emp.last_name, emp.email, emp.phone_number,
dept.manager_id
from
employee emp, department dept
where
emp.department_id = dept.department_id

Related

I get error as "duplicate key value violates unique constraint "

I'm working on a data warehouse. I have 4 table on public schema they are customer, product, addressee and orders
Then I created this tables on my olap schema
CREATE TABLE olap.time
(
idtime SERIAL NOT NULL PRIMARY KEY,
year integer,
month integer,
week integer,
day integer
);
CREATE TABLE olap.addressees
(
idaddressee integer PRIMARY KEY NOT NULL,
name varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(60) NOT NULL
);
CREATE TABLE olap.customers
(
idcustomer varchar(10) PRIMARY KEY ,
name varchar(40) NOT NULL,
city varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(40) NOT NULL,
email varchar(40),
phone varchar(16) NOT NULL,
regon char(9)
);
CREATE TABLE olap.fact
(
idtime integer NOT NULL,
idaddressee integer NOT NULL,
idcustomer varchar(10) NOT NULL,
idfact integer NOT NULL,
price numeric(7,2),
PRIMARY KEY (idtime, idaddressee, idcustomer),
FOREIGN KEY (idaddressee) REFERENCES olap.addressees(idaddressee),
FOREIGN KEY (idcustomer) REFERENCES olap.customers(idcustomer),
FOREIGN KEY (idtime) REFERENCES olap.time(idtime)
);
After the creating tables I run these queries
INSERT INTO olap.time (year, month, week, day)
SELECT date_part('year', date), date_part('month', date), date_part('week', date), date_part('day', date)
FROM public.orders
GROUP BY public.orders.date
ORDER BY public.orders.date;
INSERT INTO olap.addressees(idaddressee, name, zip, address)
SELECT idaddressee, name, zip, address
FROM public.addressee;
INSERT INTO olap.customers (idcustomer, name, city, zip, address, email, phone, regon)
SELECT idcustomer, name, city, zip, address, email, phone, regon
FROM public.customer;
And then I try to do these set of query
INSERT INTO olap.fact (idtime, idaddressee, idcustomer, idfact, price)
SELECT olap.time.idtime, olap.addressees.idaddressee, olap.customers.idcustomer, COUNT(*), public.orders.price
FROM (((public.orders
INNER JOIN olap.time ON (date_part('year', public.orders.date) = olap.time.year AND date_part('month', public.orders.date) = olap.time.month AND date_part('week', public.orders.date) = olap.time.week) AND date_part('day', public.orders.date) = olap.time.day)
INNER JOIN olap.addressees ON public.orders.idaddressee = olap.addressees.idaddressee)
INNER JOIN olap.customers ON public.orders.idcustomer = olap.customers.idcustomer)
GROUP BY olap.time.idtime, olap.addressees.idaddressee, olap.customers.idcustomer, public.orders.price;
After running last set of queries I got error
ERROR: syntax error at or near "duplicate"
LINE 1: duplicate key value violates unique constraint"
What can the problem be? Thanks in advance

Passing UUID of one table to another table as a Foreign key value in PostgreSQL

I have table Employee in Postgres:
drop table if exists employee;
create table employee (
id uuid default uuid_generate_v4 () primary key,
first_name varchar not null,
last_name varchar not null
);
And another table salary :
drop table if exists salary;
create table salary (
check_id uuid default uuid_generate_v4 () primary key,
salary int not null,
employee_id uuid references employee (id)
);
employee_id is the foreign key to id in the Employee table, but I don't understand how to insert a value inside employee_id since UUID is unique.
I am inserting values into Employee table:
insert into employee (first_name, last_name, email, code) values ( 'jonh', 'smith', 'jonh#example.com', '1');
And then if I try insert values into salary table:
insert into salary (salary ) values ('1000');
Then select command will return employee_id value empty.
But if I make it default uuid_generate_v4 (), then result is: Key (employee_id)=(c4ccd745-02ba-4a0e-8586-32e3c6a2b84a) is not present in table "employee".
I understand that because employee_id is a foreign key it should match with uuid in employee, but since uuid is mostly unique, how can I make it work?
You have to use the uuid that was inserted into the employee table. You can do this with a CTE in a single statement:
WITH new_employee AS (
INSERT INTO employee (first_name, last_name, email, code)
VALUES ('jonh', 'smith', 'jonh#example.com', '1')
RETURNING id
)
INSERT INTO salary (salary, employee_id)
SELECT 1000, id
FROM new_employee;

Find top salary per department - is there a more efficient query?

I have a query that works but I suspect I'm doing this inefficiently. Is there a more elegant approach to find the top salary in each department and the employee that earns it?
I'm doing a cte to find the max salary per dept id and then join that up with the employee data by matching salary and dept id. I have code below to build/populate the tables and the query at the end.
CREATE TABLE employee (
emplid SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
salary FLOAT NOT NULL,
depid INTEGER
);
INSERT INTO employee (name, salary, depid)
VALUES
('Chris',23456.99,1),
('Bob',98756.34,1),
('Malin',34567.22,2),
('Lisa',34967.73,2),
('Deepak',88582.22,3),
('Chester',99487.41,3);
CREATE TABLE department (
depid SERIAL PRIMARY KEY,
deptname VARCHAR NOT NULL
);
INSERT INTO department (deptname)
VALUES
('Engineering'),
('Sales'),
('Marketing');
--top salary by department
WITH cte AS (
SELECT d.depid, deptname, MAX(salary) AS maxsal
FROM employee e
JOIN department d ON d.depid = e.depid
GROUP BY d.depid, deptname
)
SELECT cte.deptname, e.name, cte.maxsal
FROM cte
JOIN employee e ON cte.depid = e.depid
AND e.salary = cte.maxsal
ORDER BY maxsal DESC;
Here is the target result:
"Marketing" "Chester" "99487.41"
"Engineering" "Bob" "98756.34"
"Sales" "Lisa" "34967.73"
In Postgres this can solved using the distinct on () operator:
SELECT distinct on (d.depid) d.depid, deptname, e.name, e.salary AS maxsal
FROM employee e
JOIN department d ON d.depid = e.depid
order by d.depid, e.salary desc;
Or you can use a window function:
select depid, deptname, emp_name, salary
from (
SELECT d.depid,
deptname,
e.name as emp_name,
e.salary,
max(e.salary) over (partition by d.depid) AS maxsal
FROM employee e
JOIN department d ON d.depid = e.depid
) t
where salary = maxsal;
Online example: https://rextester.com/MBAF73582
You should have an index:
create index employee_depid_salary_desc_idx on employee(depid, salary desc);
And then use the following query that can use the index:
select
depid,
deptname,
(
select
emplid
from employees
where depid=department.depid
order by salary desc
limit 1
) as max_salaried_emplid
from department;
(A join for retrieving data from the emplid left as an exercise for the reader).

Select rows conditionally and insert into another table conditionally

How to insert into table 2 all field values of a row from table A, where all values in a column A in table 1 that satisfy a condition on column B of table 1 ,but do not exist in table 2.How to frame a query using not exists?
I tried this:
INSERT INTO Teachermast (
teacher_code,
teacher_name,
designation,
dept_code,
contact_no,
email,
address,
dob,
PASSWORD
)
SELECT
userId,
username,
designation,
dept,
contact_no,
email,
address,
dob,
PASSWORD
FROM
UserMast
WHERE NOT EXISTS
(SELECT
userId
FROM
UserMast
WHERE usertype = '3')
but this doesnt seem to work.
Kindly help.
You could do a MERGE
create table users
(
userId varchar(50),
username varchar(50),
usertype int,
password varchar(50),
contact_no varchar(50),
email varchar(50),
faxno varchar(50),
address varchar(50),
created_date date,
updated_date date,
status varchar(50),
gender varchar(50),
dob date,
lasttimelogin datetime,
login_time datetime,
logoutt_time datetime,
designation varchar(50),
dept varchar(50),
email_pass varchar(50)
)
insert into users values('T0003','Ankita',3,'12345','9858‌​585245','anki#gmail.com','201','l block noid sec 25',NULL,NULL,NULL,'Female','11/09/1990',NULL,NULL,NULL,'Teacher','EC',NULL);
insert into users values('T0004','Ribha',3,'12345','9512365423','sharma#gmail.com',NULL,'221 dwarka sec 10',NULL,NULL,NULL,'Female','12/02/1989',NULL,NULL,NULL,'Teacher','EC',NULL);
create table teachers
(
teacher_code varchar(50),
teacher_name varchar(50),
designation varchar(50),
dept_code varchar(50),
contact_no varchar(50),
email varchar(50),
address varchar(50),
dob date,
password varchar(50)
)
insert into teachers values('T0002','Tanvi','Teacher','CS','9632569856','tan123#gmai‌​l.com','298 mayur vihar ph 1','29/06/1990','12345');
insert into teachers values('T0003','Ankita','Teacher','EC','9858585245','anki#gmail‌​.com','201 l block noida sec 25','11/09/1990','12345');
merge teachers as target
using (select userid, username, designation, dept, contact_no, email, address, dob, password from users where usertype = 3)
as source(userid, username, designation, dept, contact_no, email, address, dob, password)
on target.teacher_code = source.userid
when not matched by target then
insert (teacher_code, teacher_name, designation, dept_code, contact_no, email, address, dob, password)
values (source.userid, source.username, source.designation, source.dept, source.contact_no, source.email, source.address, source.dob, source.password);
select * from teachers
However, I think there are issues with your database design. With your current model, you could have, for example, a different address (or password!) for Ankita in table1 compared to table2. And if you change any of that information you would have to change it in both places.
Could you, for example, just insert everyone into "users" and have "teachers" be a view
select {columns} from users where usertype = 3
Please try this query
SELECT
t.userId,
t.username,
t.designation,
t.dept,
t.contact_no,
t.email,
t.address,
t.dob,
t.PASSWORD
FROM Teachermast as t
LEFT join UserMast as u on t.userId = u.teacher_code
WHERE t.usertype = '3' and u.teacher_code is null

How to execute multiple query one by one

table_1 (id, first_Name, last_Name)
table_2 (id, name, table_1_id)
My work is to copy all values of a column from table_1 to table_2 as individual entry. My query is
Query_1:
insert into table_2 ( name, table_1_id )
select first_Name as name, id as table_1_id from table_1.
My other query is
Query_2:
insert into table_2 ( name, table_1_id )
select last_Name as name, id as table_1_id from table_1.
It run pretty good but save all first_name then save all last_name.
my requirement is to run these two queries together and want the result will be like
first_Name(whatever) table_1_id (1)
last_Name(whatever) table_1_id(1)
first_Name(whatever) table_1_id(2)
last_Name(whatever) table_1_id(2)
Thanks in advance
Note: table_1_id is not a foreign key in table_2
Try by using WITH Queries (Common Table Expressions)
WITH cte AS (
insert into table_2 ( name, table_1_id )
select first_Name as name, id as table_1_id from table_1
)
insert into table_2 ( name, table_1_id )
select last_Name as name, id as table_1_id from table_1
and test values by select * table_2 order by table_1_id
You can achieve this using an union all:
INSERT INTO table_2( name, table1_id)
select name, id from
(
select first_name as name, id from table_1
union all
select last_name as name, id from table_1
) A
order by id