Consider the tables CUSTOMER, ORDER and PRODUCT given below:
Table: CUSTOMER
CID |
CName |
Address |
Phone |
C01 |
Anil |
Delhi |
9876543210 |
C02 |
Bina |
Mumbai |
8765432109 |
C03 |
Chetan |
Kolkata |
7654321098 |
C04 |
Divya |
Chennai |
6543210987 |
C05 |
Esha |
Hyderabad |
5432109876 |
Table: ORDER
OID |
Date |
Amount |
CID |
PID |
O01 |
01-01-2020 |
5000 |
C01 |
P01 |
O02 |
02-02-2020 |
8000 |
C02 |
P02 |
O03 |
03-03-2020 |
3000 |
C03 |
P03 |
O04 |
04-04-2020 |
4000 |
C04 |
P04 |
O05 |
05-05-2020 |
6000 |
C05 |
P05 |
O06 |
06-06-2020 |
7000 |
C01 |
P06 |
O07 |
07-07-2020 |
9000 |
C02 |
P07 |
Table: PRODUCT
PID |
PName |
Category |
Price |
P01 |
Laptop |
Electronics |
50000 |
P02 |
Sofa |
Furniture |
20000 |
P03 |
Book |
Stationery |
500 |
P04 |
Mobile |
Electronics |
15000 |
P05 |
Table |
Furniture |
10000 |
P06 |
Printer |
Electronics |
10000 |
P07 |
Chair |
Furniture |
5000 |
Write SQL queries for the following:
(i) Display customer name and order date from the tables CUSTOMER and ORDER.
Answer:
Answer by student
SELECT CName, Date FROM CUSTOMER, ORDER WHERE CUSTOMER.CID = ORDER.CID;
Detailed answer by teachoo
-lock-
To display customer name and order date from the tables CUSTOMER and ORDER, we need to use the SELECT statement in SQL. The syntax of this statement is:
SELECT column_name(s) FROM table_name(s) WHERE condition(s);
- In this case, we want to select the CName column from the CUSTOMER table and the Date column from the ORDER table. We also need to specify the condition that the CID column of the CUSTOMER table matches the CID column of the ORDER table. This is called a join condition that links the two tables based on a common attribute. We use the WHERE clause to specify the condition. So, we write:
SELECT CName, Date FROM CUSTOMER, ORDER WHERE CUSTOMER.CID = ORDER.CID;
- Here, we use a comma to separate the two table names in the FROM clause. This is called a cross join or a Cartesian product that combines every row of one table with every row of another table. However, by using the WHERE clause, we filter out only those rows that satisfy the join condition. This is called an inner join or an equi-join that returns only those rows that have matching values in both tables.
- Alternatively, we can also use the JOIN keyword to perform an inner join. The syntax of this statement is:
SELECT column_name(s) FROM table_name1 JOIN table_name2 ON condition(s);
- In this case, we write:
SELECT CName, Date FROM CUSTOMER JOIN ORDER ON CUSTOMER.CID = ORDER.CID;
- Here, we use the ON clause to specify the join condition. This is equivalent to the previous query.
-endlock-