Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

MySQL – It is an open source RDBMS.

It is used at the backend to manage the data stored in the


database. There are two components of MYSQL: SQL commands and Database. SQL stands for
Structured Query Language and database is a collection of tables.
SQL is a non-procedural language that uses a predefined a set of programs called commands to
retrieve and manipulate data in the database. These commands are not case sensitive and are
categorized under 4 heads:
1. DDL commands – Data Definition Language, a set of commands that are used to modify the
structure of a table. Example: create table, drop table, alter table
2. DML commands – Data Manipulation language, a set of commands that are used to modify
the contents of a table. Example: select, insert, delete and update
3. DCL commands – Data Control Language, a set of commands that are used to control the
access of the data in the database. Example: grant, revoke
4. TCL commands – Transaction Control Language, a set of commands that are used to control
the transaction issued on the database. Example: commit, rollback

Few important terminologies:


1. Database: a collection of tables
2. Relation: It is a table of data
3. Table: A collection of data stored in a format of rows and columns.
4. Attribute: A column of a table
5. Tuple: A row of a table
6. Cardinality: Total number of rows in a table
7. Degree: Total number of columns of a table
8. Candidate key: An attribute or a set of attributes that is used to uniquely identify a tuple of a
relation. All such keys are called candidate keys that are eligible to form a primary key.
9. Alternate key: Any candidate key which is not a primary key is called an alternate key.
10. Primary key: The candidate key which is selected as the programmer to uniquely identify a
tuple of a relation. It cannot be NULL and cannot have repeating values.
11. Foreign key: An attribute of a table is called as a foreign key if it is a primary key of another
table. It can have values if it exists in the primary key attribute of the other table. It can be
repeating and cannot have NULL values.
12. Referential Integrity: This talks of the integrity that is built with the help of primary-foreign
key relationship. It avoids duplication of values and get rids of any anomalies created with
deletion of tuples.
13. Constraint: It is a check created for the data validation during creating a table. Certain rules
are placed on the attributes of a table to avoid invalid data entry as per the requirement.
a. Not null – it ensures that an entry is not null or kept blank.
b. Unique – It ensures that an entry is non repeating. It can accept only one NULL value.
c. Primary – it ensures that the entry is not duplicate and is not null.
d. Foreign – It ensures referential integrity.
Page 1 of 14
e. Enum – It ensures that an element of the set defined is only a valid entry.
f. Check – It ensures that an entry satisfies the condition given in the check constraint.
g. Default – It ensures that if the entry is skipped the default values goes into it.

Example of a query with all the constraints


Create table student(roll in primary key, name varchar(20), age int unique, city char(10) default
‘Delhi’, marks decimal(5,2) check(marks>=0 and <=100), grade enum (‘A’,’B’,’C’,’D’));

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

Roll Name Age Roll Name Age

101 Rohit 16 201 Ram 16

102 John 17 202 Shyam 17

103 Soham 18 103 Soham 18

104 Sidd 16 203 Babita 19

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

R3=8 R1+R2-no. of duplicate rows), C3=3 (C1 or C2)

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

Roll Name City Pcode Rating

101 Rohit Delhi 100058 A

102 John Kolkata 700047 B

103 Soham Pune 400501 C

Kolkata 700075 B
R1=3, C1=2

R2=4, C2=3

Query: Select * from A, B;

Table: AXB ( Cartesian Product )

Roll Name City Pcode Rating

101 Rohit Delhi 100058 A

101 Rohit Delhi 700047 B

Page 3 of 14
101 Rohit Delhi 400501 C

101 Rohit Delhi 700075 B

102 John Kolkata 100058 A

102 John Kolkata 700047 B

102 John Kolkata 400501 C

102 John Kolkata 700075 B

103 Soham Pune 100058 A

103 Soham Pune 700047 B

103 Soham Pune 400501 C

103 Soham Pune 700075 B

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

Roll Name Class stream Marks


1 Rohit 12 Science 89
2 Samal 11 NULL 67
3 Gaurav 12 Commerce 90
4 Anil 12 Science 75
5 Sunil 11 Arts 65

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;

2) Distinct – unique column(s)


select distinct(name) from student;

3) Where – specific rows


select * from student where class=11;

4) And, or, not – logical operators to combine conditions


select * from student where class=11 and stream=”arts”;

5) <,>,<=,>=,=,!= - comparison operators to build condition


select * from student where class>11;

6) As, is, null, formula


select roll as “serial number” 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;

11) Aggregate functions: count(), max(), min(), avg() and sum()


select max(marks) from student;
select min(marks) from student;
select sum(marks) from student;
select count(*) from student;
select avg(marks) from student;

12) Adding and deleting a column


Alter table student add column address char(30);
Alter table student drop column address;

13) Changing the column datatype


Alter table student modify marks decimal(6,2);

14) Modifying a column name


Alter table student change address add char(20);

15) Adding a primary key


Alter table student add primary key(roll);

16) Removing a primary key


Alter table student drop primary key;

17) Deleting all the rows


Page 6 of 14
Delete from student;

18) Deleting specific rows


Delete from student where marks<=40;

19) Updating all the rows


Update student set marks=marks+10;

20) Updating specific rows


Update student set marks=90 where roll=5;

21) Updating multiple column values


Update student set marks=97, stream=’science’ where roll>3;

22) Counting: nulls are not counted


Select count(stream) from student;

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 |

Cartesian product on two tables


We learnt that application of operator cartesian product on two tables results in a table having all
combinations of tuples from the underlying tables. When more than one table is to be used in a
query, then we must specify the table names by separating commas in the FROM clause. On
execution of such a query, the DBMS (MySql) will first apply cartesian product on specified tables to
have a single table.
DANCE

| SNo | Name | Class |

Page 8 of 14
| 1| Aastha | 7A |

| 2| Mahira | 6A |

| 3| Mohit | 7B |

| 4| Sanjay | 7A |

MUSIC

| SNo | Name | Class |

| 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 |

JOIN on two tables


JOIN operation combines tuples from two tables on specified conditions. This is unlike cartesian
product, which make all possible combinations of tuples. While using the JOIN clause of SQL, we
specify conditions on the related attributes of two tables within the FROM clause. Usually, such an
attribute is the primary key in one table and foreign key in another table. Let us create two tables
UNIFORM (UCode, UName, UColor) and COST (UCode, Size, Price) in the SchoolUniform database.
UCode is Primary Key in table UNIFORM. UCode and Size is the Composite Key in table COST.
Therefore, Ucode is a common attribute between the two tables which can be used to fetch the
common data from both the tables. Hence, we need to define Ucode as foreign key in the Price table
while creating this table.

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.

Linked tables using primary key foreign key relationship


student teacher
Roll Name Class stream Tid Tname Age Roll Gender
1 Rohit 12 Science 101 Raj 47 2 M
2 Samal 11 Arts 102 Yogesh 52 3 M
3 Gaurav 12 Commer 103 Mohini 53 1 F
ce 104 Naveen 41 2 M
4 Anil 12 Science
5 Sunil 11 Arts

To create table student

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));

Few queries on join:


1. To display student names and their teacher names.
Select name, tname from student, teacher where student.roll=teacher.roll;
2. To count the number of students taught by male teachers only.
Select count(*) from student,teacher where student.roll=teacher.roll and gender=’M’;

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);

mysql> insert into customer


values(101,'anilkumar',1,8090,'delhi','2019/02/12','computer','m',20980);
mysql> insert into customer
values(102,'ravikumar',2,5490.76,'delhi','2018/07/23','keyboard','m',34908);
mysql> insert into customer
values(103,'sohailkhan',3,6789.76,'mumbai','2019/2/10','keyboard','m',5690);
mysql> insert into customer
values(104,'romikhan',4,5000.26,'kolkata','2017/8/13','mouse','f',12345);
mysql> insert into customer values(105,'kashish',1,5990.50,'chennai','2019/3/13','mic','f',43290);
mysql> insert into customer
values(106,'ronitroy',2,8000.50,'mumbai','2019/10/15','headphone','m',21456);
mysql> insert into customer values(107,'bauldas',5,null,'delhi','2018/1/1','headphone','m',19870);
mysql> insert into customer values(108,'rubyroy',2,2090.78,'kolkata','2017/8/28','laptop','f',21908);

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

You might also like