How to perform FULL JOIN, LEFT JOIN and RIGHT JOIN in PostgreSQL [closed] - postgresql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to PostgreSQL. We have given an activity to perform FULL JOIN, LEFT JOIN, AND RIGHT JOIN. I have an answer but I am not sure if it is right. I need some help to correct me.
These are the questions and my answers.
Perform a FULL JOIN on staff and staff_ph TABLE WHERE region_id is 8 AND sort from the highest salary to the lowest salary.
SELECT *
FROM staff FULL JOIN staff_ph
ON staff.id = staff_ph.id
WHERE staff.region_id = 8
ORDER BY staff.salary DESC;
Perform a LEFT JOIN on staff and staff_ph TABLE WHERE region_id is 8 AND sort by last_name.
SELECT *
FROM staff LEFT JOIN staff_ph
ON staff.id = staff_ph.id
WHERE staff.region_id = 8
ORDER BY staff.last_name DESC;
Perform a RIGHT JOIN on staff and staff_ph TABLE WHERE region_id is 8 AND sort by gender.
SELECT *
FROM staff RIGHT JOIN staff_ph
ON staff.id = staff_ph.id
WHERE staff.region_id = 8
ORDER BY staff.gender DESC;

Your FULL JOIN and RIGHT JOIN don't make much sense, since you then filter out the rows where staff.region_id was fabricated as NULL. On the other hand, it seems to be the question, not your answer, that is to blame for this. Maybe the intention was for that condition to go in the ON, not the WHERE.

Related

Postgresql how to use union for two selects in the same table? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have one table:
id
created_at
author
1
02.02.2020
manager
2
02.02.2020
client
3
02.02.2020
manager
I want to get result like below, and date sorted:
date
manager
client
02.02.2020
2
1
03.02.2020
5
3
I tried:
SELECT created_at::date, count(id) AS manager FROM orders where author = 'manager' GROUP BY created_at::date
union
SELECT created_at::date, count(id) AS client FROM orders where author = 'client' GROUP BY created_at::date
And I got:
date
manager
03.02.2020
2
02.02.2020
5
You don't need a union, this can be done in a single query using a filtered aggregate:
select created_at::date,
count(*) filter (where author = 'manager') as managers,
count(*) filter (where author = 'client') as clients
from orders
group by created_at::date
order by created_at::date

How to execute a PostgreSQL with "WITH" statement? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I need to execute a query with WITH statement. If I run it, my WITH data shows error. This is my sample query please guide me to execute it.
with
x1_fields as
(SELECT
x1.id as x_id,
x1.created_time as x_created,
sum(x1.value) as x_sum
FROM
xxxx1 x1
INNER JOIN xxxx2 x2 ON x2.id = x1.id
INNER JOIN xxxx3 x3 ON x3.id = x2.id
WHERE
x1.customer = 'microsoft'
GROUP BY
x1.id,
x1.created_time
)
SELECT
y.id as final_id,
x_t.sum as final_sum
FROM
yyyy as y
left join x1_fields as x_t on x_t.x_id = y.id
where
y.customer = 'microsoft'
and y.id = '123456'
I have try to run this query in DBeaver but I can't run this. But it works in SSRS. I need to check such queries in some SQL software and debug it. Please give me some instructions to solve this.
Since we don't know your database and table structure, we cannot find an error which might occure because of wrong relation names or something.
However: Syntax error is the , character after the WITH clause (before the final SELECT). You have to remove it.

How to increase the speed sql query and get fastly record [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a large set of records in my database. I tried to run SQL query using where condition. I got the data and I show count of records also. It taking around 21 secs. I need to reduce the time.
Sql Query
select * from sample_rank where company_id = 1
Records Count
166270266
I added Index in db. but It's not fastly getting data. How to fix it and How to change the query
Assuming, going by your comments, that you only need to select two of the columns in your table:
SELECT col1, col2 FROM sample_rank WHERE company_id = 1;
then the following covering index is probably the best you can do here:
CREATE INDEX idx ON sample_rank (company_id, col1, col2);
The above index completely covers the entire query, meaning that, if used, your SQL engine can use the index alone to satisfy the entire query plan. I put "if" in bold, because depending on the cardinality of the data, the above index might not help the query run faster. For example, if you only have two company_id values, 1 and 2, with 50% of the record having each value, then your SQL engine might just decide that a full table scan would be faster than even resorting to use the index. As suggested in the comments, running EXPLAIN on your actual query would reveal more information.

print the 1 to 10 numbers using Table [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to print the 1 to 10 numbers based on table.
Table1
A
null
outout is
1
2
3
4
.
.
10
I have a table that table contains only one record...using this table i want to print 1 to 10 numbers please tell me
I written like this...is there any alternate way to write this
select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 from table1;
or
select generate_series(1,10) from table1;
Because your question is almost devoid of useful information, I don't feel bad simply presenting a link to the docs. Take a look at generate_series()
http://www.postgresql.org/docs/current/static/functions-srf.html

Stuck on a query and need support to improve the performance (if any) for the execution !(PostgreSQL)? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to PostgreSQL and I am learning by taking few examples!
I am solving a queries in PostgreSQL and I came with few but got stuck at one point!
Given the sample data in the SQLFiddle below, I tried:
--6.find most sold product with with sales_id, product_name,quantity and sum(price)
select array_agg(s.sale_id),p.product_name,s.quantity,sum(s.price)
from products p
join sales s
on p.product_id=s.product_id;
but it fails with:
ERROR: column "p.product_name" must appear in the GROUP BY clause or be used in an aggregate function:
This is the SQL Fiddle with sample data.
I'm using PostgreSQL 9.2.
For all that it looks simple, this is quite an interesting problem.
The unsolved #6
There are two stages to this:
find the most sold product; and
display the required detail on that product
The question is badly written; it fails to specify whether you want
the product with the greatest number of sales, or the greatest
dollar sales value. I will assume the former, but it's easy to adapt the following queries to sort by total price instead.
UPDATE: #user2561626 found the simple solution I mentioned I was sure I was overlooking but couldn't think of: http://sqlfiddle.com/#!12/dbe7c/118 . Use the output of SUM in ORDER BY then LIMIT the result set.
The following are the complicated and roundabout ways I tried because I couldn't think of the simple way:
One way is to use a subquery with an ORDER BY and LIMIT to sort products by total number of sales, then pick the top one. You then join on that inner query to generate the desired product summary. In this case I join on sales twice, once in the inner query and once in the outer where I calculate more detail for just one product. It's possibly more efficient to join on it just once in the inner query and do more work, but that'll involve creating and discarding a bigger result set, so it's the sort of thing you'd tune based on your data distribution.
SELECT
array_agg(s.sale_id) AS sales_ids,
(SELECT p.product_name FROM products p WHERE p.product_id = pp.product_id) AS product_name,
sum(s.quantity) AS total_quantity,
sum(s.price) AS total_price
FROM
(
-- Find the product with the largest number of sales
-- If multiple products have the same sales an arbitrary candidate
-- is selected; extend the ORDER BY if you want to control which
-- one gets picked.
SELECT
s2.product_id, sum(s2.quantity) AS total_quantity
FROM sales s2
GROUP BY s2.product_id
ORDER BY 2 DESC
LIMIT 1
) AS pp
INNER JOIN sales s ON (pp.product_id = s.product_id)
GROUP BY s.product_id, pp.product_id;
I'm honestly not too sure how to phrase this in purely standard SQL (i.e. no LIMIT clause). You can use a CTE or multiple scans in subqueries to find the greatest number of sales and the product Id with the greatest number of sales, but that'll give you multiple results if you have more than one product with equal sales.
I can't help but feel I've totally forgotten the simple and obvious way to do this.
Comments on others:
--1.write the query find the products which are not soled
select *
from products
where product_id not in (select distinct PRODUCT_ID from sales );
Your solution is subtly incorrect, because there's no NOT NULL constraint on product_id in sales. It builds a list then filters on the list, but the list could contain NULL, and 2 NOT IN (1, NULL) is NULL, which in WHERE is treated as false.
It is much better to re-phrase this as WHERE NOT EXISTS (SELECT 1 FROM sales s WHERE s.product_id = products.product_id).
With #2 it's again better to use EXISTS, but PostgreSQL can optimize it into the better form automatically since it's semantically the same; the NULL issue doesn't apply for IN, only NOT IN. So your query is fine.
Question #7 highlights that this is an awful schema. You should never store split-up year/month/day like this; a sale would just have a single timestamptz field, and to get the year you'd use date_trunc or extract. That's not your fault, it's bad table design in the question. The question could also be clearer; I think you've answered it correctly as written, but they don't say whether or not years with no sales should be shown - presumably they assume there aren't any. If there are, you'd have to do a left outer join over a generate_series of dates to zero-fill empty years.
Question #8 is another bad question, frankly. "max price". Um. What? "Maximum price paid per item" would be "price/quantity". "Greatest total individual sale value for each product" would be what you wrote. The question seems to allow for either.
The Query Solution for Question#6 is ::
select array_agg(s.sale_id),p.product_name,sum(s.quantity) as Quantity ,sum(s.price) as Total_Price
from sales s,products p
where s.product_id =p.product_id
group by p.product_id
order by sum(s.quantity) desc limit 1 ;
Comment On Others
Question#9: #Robin Hood's
select s.sale_id,p.product_name,s.quantity,s.price
from products p,sales s
where p.product_id=s.product_id and p.product_name LIKE 'S%';
the 'S%' is a case Sensitive .. so it how it works..
Question#10: #Robin Hood's
Stored Procedure is:
CREATE OR REPLACE FUNCTION get_details()
RETURNS TABLE(sale_id integer,product_name varchar,quantity integer,price int) AS
$BODY$
BEGIN
RETURN QUERY
select s.sale_id,p.product_name,s.quantity,s.price
from products p
join sales s
on p.product_id =s.product_id ;
Exception WHEN no_data_found then
RAISE NOTICE 'No data available';
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
select * from get_details(); then you will get the result.
I need a help over these questions even !! i just want to add these queries to.
--Question#9
--9. select product details with sales_id, product_name,quantity and price those product names are started with letter ā€˜sā€™
--This selects my product details
select s.sale_id,p.product_name,s.quantity,s.price
from products p,sales s
where p.product_id=s.product_id ;
--This is'nt working to find those names which start with s.. is there any other way to solve this..
select s.sale_id,p.product_name,s.quantity,s.price
from products p,sales s
where p.product_id=s.product_id and product_name = 's%';
--10. write the stored procedure for extract all the sales and product details with sales_id, product_name,quantity and price with exception handling and raisint the notices