PostgreSQL Q&A

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

CREATE TABLE Products ( ProductID INT PRIMARY KEY, ProductName

VARCHAR(50), CategoryID INT, Price DECIMAL(10, 2) );

CREATE TABLE
Categories ( CategoryID INT PRIMARY KEY, CategoryName VARCHAR(50) );

CREATE TABLE Orders ( OrderID INT PRIMARY KEY, OrderDate DATE, CustomerID
INT );

CREATE TABLE OrderDetails ( OrderDetailID INT PRIMARY KEY, OrderID


INT, ProductID INT, Quantity INT, Price DECIMAL(10, 2) );

CREATE TABLE
Customers ( CustomerID INT PRIMARY KEY, CustomerName VARCHAR(50), Address
VARCHAR(100), Phone VARCHAR(20) ); INSERT INTO Products (ProductID,
ProductName, CategoryID, Price) VALUES (1, 'Screwdriver', 1, 5.99), (2,
'Hammer', 1, 9.99), (3, 'Wrench', 1, 7.99), (4, 'Drill', 2, 49.99), (5,
'Saw', 2, 39.99); INSERT INTO Categories (CategoryID, CategoryName)
VALUES (1, 'Hand Tools'), (2, 'Power Tools'); INSERT INTO Customers
(CustomerID, CustomerName, Address, Phone) VALUES (1, 'John Smith', '123
Main St, Anytown', '555-1234'), (2, 'Jane Doe', '456 Elm St, Othertown',
'555-5678'), (3, 'Oppen', '520 ply St, Thery', '666-8796'); INSERT INTO
Orders (OrderID, OrderDate, CustomerID) VALUES (1, '2024-04-01', 1), (2,
'2024-04-02', 2); INSERT INTO OrderDetails (OrderDetailID, OrderID,
ProductID, Quantity, Price) VALUES (1, 1, 1, 2, 5.99), (2, 1, 2, 1,
9.99), (3, 2, 3, 1, 7.99), (4, 2, 4, 1, 49.99), (5, 2, 4, 3, 49.99);

Select c.customername
FROM customers c
LEFT JOin orders o
ON c.customerid = o.customerid
WHERE orderdate ='2024-04-01';

-----List all orders along with the customer name for each order ------

SELECT c.customername, o.orderid, o.orderdate


FROM customers c RIGHT JOIN orders o ON c.customerid = o.customerid;

---Retrieve the details of customers who have not placed any orders.---
SELECT* FROM customers AS c
LEFT JOIN orders AS o ON c.customerid = o.customerid
WHERE orderid is null

-- Sub query
select *
from customers
where customerid not in
(select distinct customerid from
orders)

--Find the average price of products in each category--


SELECT ct.categoryname, round(AVG(p.price),2) AS Average_Price
FROM categories ct JOIN products p
ON ct.categoryid = p.categoryid
group
by ct.categoryname

You might also like