Mysql Final
Mysql Final
14. Union – This is a type of join operation that is applied to two tables, the result table has
number of rows that is the sum of the number of rows of the two tables subtracting the
number of duplicate rows in both and number of columns as the sum of the number of
columns of any of the two tables. There is a pre requirement to the union operation and that
is:
1) Both tables must have same number of columns
2) The data types of the corresponding attributes of the two tables must be same.
Table: 12A_Eng Table: 12B_Eng
204 Rupam 17
R1=4, C1=3
R2=5, C2=3
Query: Select * from A union select * from B;
Table: A U B ( Union )
Roll Name Age
101 Rohit 16
102 John 17
103 Soham 18
104 Sidd 16
201 Ram 16
Page 2 of 14
202 Shyam 17
203 Babita 19
204 Rupam 17
15. Cartesian product: This is product operation that is applied to two tables, the result table has
number of rows that is the product of the number of rows of the two tables and number of
columns as the sum of the number of columns of two tables.
Table: A Table: B
Kolkata 700075 B
R1=3, C1=2
R2=4, C2=3
Page 3 of 14
101 Rohit Delhi 400501 C
R3=12(R1*R2), C3=3(C1+C2)
Datatypes:
int/ int(<size>)
decimal/decimal(<total places>, <number of places after decimal point)
date
char(<number of characters>
varchar(<number of characters>)
Various commands:
1. To display all the names of databases that exist
show databases;
2. To remove the database
drop database <name>;
3. To create a database
create database <name>;
4. To enter into a database
use <database name>;
5. To display all the table names
show tables;
Page 4 of 14
6. To remove a table
drop table <name>;
7. To create a table
create table <name>(<datatype> <colname1><constraint optional>, <datatype> <colname2>, …);
8. To see the structure of a table
Desc <table name>;
9. To insert a row for all attributes in a table
insert into <tablename> values (<value1>,<value2>,<value3>,…);
10. To insert a row of specific attributes in a table
insert into <tablename>(<colname1>,<colname2>,..) values (<value1>,<value2>,..);
Table: student
The queries formed for the following SQL operators/ clauses and functions are w.r.t. the above table.
11. select command with the use of
1) * - to display all the columns
select * from student;
Page 5 of 14
select * from student where class is NULL;
select marks*3 as “total in UTs” from student;
7) Between and in
select * from student where marks between 80 and 90;
select roll from student where class in (11,10);
8) Order by
select * from student where marks > 80 order by marks desc;
select * from student order by name;
9) Like, %, _
select * from student where name like ‘__r%’;
10) Group by
select count(*), stream from student group by stream;
GROUP BY in SQL
At times we need to fetch a group of rows on the basis of common values in a column. This can be
done using a GROUP BY clause. It groups the rows together that contain the same values in a
specified column. We can use the aggregate functions (COUNT, MAX, MIN, AVG and SUM) to work on
the grouped values. HAVING Clause in SQL is used to specify conditions on the rows with GROUP BY
clause.
Consider the SALE table :
a) Find sum of Sale Price of the cars purchased by the customer having ID C0001 from table SALE.
b) Find the maximum and minimum commission from the SALE table
Page 7 of 14
CarID, CustID, SaleDate, PaymentMode, EmpID, SalePrice are the columns that can have rows with
the same values in it.
So, GROUP BY clause can be used in these columns to find the number of records of a particular type
(column), or to calculate the sum of the price of each car type.
Example
a) Display the number of cars purchased by each customer from the SALE table.
mysql> SELECT CustID, COUNT(*) "Number of Cars" FROM SALE GROUP BY CustID;
| C0001 | 2 |
| C0002 | 2 |
| C0003 | 1 |
| C0004 | 1 |
b) Display the customer Id and number of cars purchased if the customer purchased more than
1 car from SALE table.
mysql> SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID HAVING Count(*)>1;
| C0001 | 2 |
| C0002 | 2 |
c) Display the number of people in each category of payment mode from the table SALE.
mysql> SELECT PaymentMode, COUNT(PaymentMode) FROM SALE GROUP BY Paymentmode
ORDER BY Paymentmode;
| Bank Finance | 2 |
| Cheque | 1 |
| Credit Card | 2 |
| Online | 1
d) Display the PaymentMode and number of payments made using that mode more than once.
mysql> SELECT PaymentMode, Count(PaymentMode) FROM SALE GROUP BY Paymentmode
HAVING COUNT(*)>1 ORDER BY Paymentmode;
| Bank Finance | 2 |
| Credit Card | 2 |
Page 8 of 14
| 1| Aastha | 7A |
| 2| Mahira | 6A |
| 3| Mohit | 7B |
| 4| Sanjay | 7A |
MUSIC
| 1| Mehak | 8A |
| 2| Mahira | 6A |
| 3| Lavanya | 7A |
| 4| Sanjay | 7A |
| 5| Abhay | 8A |
The following query applies cartesian product on the two tables DANCE and MUSIC
a) Display all possible combinations of tuples of relations DANCE and MUSIC
mysql> SELECT * FROM DANCE, MUSIC;
As we are using SELECT * in the query, the output will be having degree 6 and cardinality 20.
b) From the all possible combinations of tuples of relations DANCE and MUSIC, display only
those rows such that the attribute name in both have the same value.
mysql> SELECT * FROM DANCE D, MUSIC M WHERE D.Name = M.Name;
| 2 | Mahira | 6A | 2 | Mahira | 6A |
| 4 | Sanjay | 7A | 4 | Sanjay | 7A |
Uniform table
| Ucode | Uname | Ucolor |
Page 9 of 14
| 1 | Shirt | White |
| 2 | Pant | Grey |
| 3 | Tie | Blue |
Cost table
|Ucode| Size | Price |
| 1 | L | 580 |
| 1 | M | 500 |
| 2 | L | 890 |
| 2 | M | 810 |
List the UCode, UName, UColor, Size and Price of related tuples of tables UNIFORM and COST. The
given query may be written in three different ways as given below:
a) Using condition in where clause
mysql> SELECT * FROM UNIFORM U, COST C WHERE U.UCode = C.UCode;
As the attribute Ucode is in both tables, we need to use table alias to remove ambiguity.
b) Explicit use of JOIN clause
mysql> SELECT * FROM UNIFORM U JOIN COST C ON U.Ucode=C.Ucode;
c) Explicit use of NATURAL JOIN clause The output of queries (a) and (b) has a repetitive column
Ucode having exactly the same values. This redundant column provides no additional
information. There is an extension of JOIN operation called NATURAL JOIN which works
similar to JOIN clause in SQL, but removes the redundant attribute. This operator can be used
to join the contents of two tables if there is one common attribute in both the tables. The
above SQL query using NATURAL JOIN is shown below:
mysql> SELECT * FROM UNIFORM NATURAL JOIN COST;
It is clear from the output that the result of this query is same as that of queries written in (a)
and (b), except that the attribute Ucode appears only once.
Page 10 of 14
create table student( roll int primary key, name varchar(20), class varchar(10), stream int);
To create table teacher linked to student
create table teacher( tid int, tname varchar(20), age int, roll int, primary key(tid), foreign key(roll)
references student(roll));
Practice
mysql> create table customer(cid int(4) primary key,name varchar(15),rating int, spent decimal, city
varchar(10),dop date, item varchar(15), gender char(1), balance decimal);
Q1. Give an increment of 1000 to the customers balance staying in delhi and a decrement 500nto the
one staying in chennai.
Page 11 of 14
Q2. Delete all the customers who are born in january and has a balance <20000
Q3. Display the names of the customers in ascending order of cities and within that descending order
of the balance.
Q4. Find the number of customers from each city with the number greater than 3
Q5. Find the average of the balance of customers for each item purchased where maximum money
spent is less than 5000
Q6. Display the number of cities occupied by male customers.
Q7. Display the ids and item names of the customer having at least 5 characters in their names.
Q8. Display the average of the total money (spent + balance) before purchase for the female
customers.
Q9. Display the maximum balance and the minimum amount of the customers from delhi or chennai.
Q10. Display the cities of the customers.
Q11. Find the net amount for the male customers in descending order of names, where netamount is
calulated as 16% of money spent added to the money spent. The column heading must be
“netamount”.
Q12. Find the maximum balance of each customer.
Q13. Display the last 3 characters of the customers who name starts with ‘a’.
Q14. Display the names and ids of the customers whose money spent lies between 6000 and 8000.
Q15. Count all the customers who have purchased in the year 2019.
Q16. Display the maximum money spent of the customers with 0 balance.
Q17. Display the names of the customers who are still to spend money for an item.
Q18. Display the names preceded by ‘Mr.’ for the male customers and assign the column heading as
‘gentleman’.
Consider the following tables Student and Stream in the Streams_of_Students database. The primary
key of the Stream table is StCode (stream code) which is the foreign key in the Student table. The
primary key of the Student table is AdmNo (admission number).
student
AdmNo Name StCode
211 Jay NULL
Page 12 of 14
241 Aditya S03
290 Diksha S01
333 Jasqueen S02
356 Vedika S01
380 Ashpreet S03
stream
StCode Stream
S01 Science
S02 Commerce
S03 Humanities
a) Create the database Streams_Of_Students.
b) Create the table Student by choosing appropriate data types based on the data given in the table.
c) Identify the Primary keys from tables Student and Stream. Also, identify the foreign key from the
table Stream.
d) Jay has now changed his stream to Humanities. Write an appropriate SQL query to reflect this
change.
e) Display the names of students whose names end with the character ‘a’. Also, arrange the students
in alphabetical order.
f) Display the names of students enrolled in Science and Humanities stream, ordered by student
name in alphabetical order, then by admission number in ascending order (for duplicating names).
g) List the number of students in each stream having more than 1 student.
h) Display the names of students enrolled in different streams, where students are arranged in
descending order of admission number.
i) Show the Cartesian product on the Student and Stream table. Also mention the degree and
cardinality produced after applying the Cartesian product.
j) Add a new column ‘TeacherIncharge” in the Stream table. Insert appropriate data in each row.
k) List the names of teachers and students.
Page 13 of 14
l) If Cartesian product is again applied on Student and Stream tables, what will be the degree and
cardinality of this modified table?
Page 14 of 14