Professional Documents
Culture Documents
Database Concepts - Mysql
Database Concepts - Mysql
CONCEPTS
Basic Database concepts
Primary key: It is a key field which uniquely identifies a particular record /tuple. . For eg. in table
student, the column rollno contains unique values 1 and 2 to identify the two rows. The primary key is
non redundant i.e. it does not have duplicate values in the same table.
Candidate key: All attributes combination inside a relation that can serve as a primary key. They are
candidates for the primary key. Attributes that uniquely identifies an instance of an entity set.
Alternate key:Attributes which are not selected as primary keys.All the candidate keys other than the
primary keys of a relation are alternate keys for a relation.
Foreign Key: Foreign Key is a key that is defined as a primary key in some other relation. This key is
used to enforce referential integrity in RDBMS.
Roll no Name Address Mobileno Rfidno
12 Rahul V Dubai 050-1234567 s456
5 Rohan Dubai 050-9562411 s923
18 Rahul S Sharjah 055-4598125 s121
Characteristics of SQL
SQL can be linked to most of other high level languages that makes it first
choice for the database programmers.
Sql (Structured query language)
SQL statements are divided into 3 sub languages
• DDL (Data Definition Language) - DDL contains commands that are
used to create the tables, databases, indexes, views, sequences and
synonyms etc.
CREATE , ALTER , DROP
1. CHAR(n)
2. VARCHAR(n)
3. DATE
4. int
5. float
Data types
Data types are declared to identify the type of data stored for a
particular column or variable.
Data type Description
VARCHAR2(W) / VARCHAR(W) Variable length character up to width W.
CHAR(W) Fixed length character value of width W.
FLOAT To represent floating point decimals .
DATE Date value (Format is ‘yyyy-mm-dd’)
INT Whole numbers
DIFFERENCE BETWEEN CHAR AND VARCHAR
2. CHAR
Used to store fixed length character type data in a column. General syntax is
Char (size)
where size represents the maximum number of characters in a column. The CHAR type is fixed
length data type once the size n is declared the value of the attribute column will hold n characters.
e.g. name char(25) declares a data item name of type character of 25 size long even if the value for
tuple is entered as 10 characters it will hold the other 10 characters in memory.
3. VARCHAR/VARCHAR2
This data type is used to store variable length alphanumeric data. General syntax is,
varchar(size)
where size represents the maximum number of characters in a column but will allocate only the
characters assigned to the attribute.
e.g address varchar(50);
address is of type varchar of upto 50 characters long if the address attribute for a tuple only has 15
characters it will only occupy the 15 characters.
SQL Commands
Constraints:
1.NOT NULL
2.UNIQUE
3.PRIMARY KEY
SQL Commands
Constraints:
1. NOT NULL: Ensures that we cannot leave a column as null. That is a value has
to be supplied for that column.
e.g name varchar(25) not null;
2. UNIQUE: Constraint means that the values under that column are always
unique.
e.g Roll_no number(3) unique;
3. PRIMARY KEY: Constraint means that a column can not have duplicate values
and not even a null value.
e.g. Roll_no number(3) primary key;
The main difference between unique and primary key constraint is that a column
specified as unique may have null value but primary key constraint does not allow
null values in the column.
SQL Commands
CREATE TABLE Command:
Create table command is used to create a table in SQL. It is a DDL type of
command. The general syntax of creating a table is
create table <tablename> (
<column 1> <data type> [not null] [unique] [<column constraint>],
.........
<column n> <data type> [not null] [unique] [<column constraint>],
[<table constraint(s)>]
);
Eg :
CREATE TABLE STUD(RNO INT , NAME VARCHAR(20) , SECTION
CHAR(1) , DOB DATE , MARKS FLOAT);
Operators in SQL:
Relational Operators are used when two values are to be compared and
The simplest way to insert a tuple into a table is to use the insert statement
insert into <table> [(<column i, . . . , column j>)] values (<value i, . . . , value j>);
While inserting the record it should be checked that the values passed are of same
data types as the one which is specified for that particular column.
29
Inserting data in a table
METHOD I – Inserting all values
INSERT INTO EMPLOYEE VALUES (1, ‘ROHAN’ , ‘M’, 6500, 150, ’SHARJAH’,
0501234567, ’MANAGER’, ’D001’ ,’CRICKET’, 9);
30
DESCRIBING THE STRUCTURE OF THE TABLE
DESC EMPLOYEE ; OR DESCRIBE EMPLOYEE ;
• DROPPING A TABLE
DROP TABLE EMPLOYEE;
SHOW DATABASES;
SQL Commands
Queries:
To retrieve information from a database we can query the databases. SQL SELECT
statement is used to select rows and columns from a database/relation
SELECT Command
Selection: This capability of SQL can return you the tuples form a relation with
all the attributes.
Projection: This is the capability of SQL to return only specific attributes in the
relation. 32
STUDENT TABLE
In the above table command
Roll_ Name Cla Mark City Select * from student where name=‘rohan’;
no ss s Will give row
101 rohan x1 400 Chennai
101 Rohan XI 400 Chennai
102 Aneeta XII 390 Bengaluru So this is example of selection and If we give command
as
103 Pawan IX 298 Mysore Select name,class from student
Kumar will return the vertical subset .It will return columns
104 Rohan IX 376 Mangalore having name and class in it.
Rohan IX
Sanjay VII
Anju VIII 33
TABLE : STUDENT SQL Commands
Roll_no Name Clas Marks City SELECT Command
s SELECT * FROM student;
101 Rohan XI 400 Chennai command will display all the tuples in the relation student
102 Aneeta XII 390 Bengaluru SELECT * FROM student WHERE Roll_no <=102;
103 Pawan Kumar IX 298 Mysore The above command display only those records whose Roll_no
104 Rohan IX 376 Mangalore less than or equal to 102.
Select command can also display specific attributes from a
105 Sanjay VII 240 Mumbai
relation. Roll_no Name Clas Marks City
s
113 Anju VIII 432 Delhi
101 Rohan XI 400 Chennai
Rohan XI
SELECT name, class FROM student;
Aneeta XII
Pawan IX The above command displays only name and
Kumar
class attributes from student table.
Rohan IX
Sanjay VII
Anju VIII
34
VARIOUS SELECT STATEMENTS
SELECTING ALL THE DATA IN THE TABLE ENO EName SAL BONU Designatio
S n
SELECT * FROM EMPLOYEE; 101 Rohan 2000 100 PEON
102 Aneeta 3000 200 WORKER
SELECTING SELECTED VALUES FROM THE TABLE 103 Pawan 7000 300 MANAGER
Kumar
SELECT ENO ,ENAME,SAL,BONUS FROM EMPLOYEE; 104 Rohan 8000 400 MANAGER
SELECT DISTINCT DESIGNATION FROM EMPLOYEE; 105 Sanjay 5600 500 IT
Display the total number of records with title as 113 Anju VIII 432 Delhi
“Total Number of Records” i.e an alias
36
SQL Commands
Eliminating Duplicate/Redundant data
The above command returns,(notice rohan is not 113 Anju VIII 432 Delhi
Repeated again)
Name
Rohan
Aneeta
Pawan Kumar
Sanjay
37
Anju
SQL Commands
Roll_n Name Clas Marks City
o s
101 Rohan XI 400 Chennai
Conditions based on a range
102 Aneeta XII 390 Bengaluru
SQL provides a BETWEEN operator that defines a range of values that
the column value must fall for the condition to become true. 103 Pawan IX 298 Mysore
Kumar
e.g. SELECT Roll_no, name FROM student WHERE Roll_no
104 Rohan IX 376 Mangalore
BETWEEN 100 AND 103;
The above command displays Roll_no and name of those students whose 105 Sanjay VII 240 Mumbai
Roll_no lies in the range 100 to 103 (both 100 and 103 are included in the
113 Anju VIII 432 Delhi
range).
displays those records whose Roll_no starts with 1 and second letter
may be any letter but ends with digit 3.
39
SELECTION USING WILD CARD PATTERNS % AND _(UNDERSCORE)
SELECT * FROM EMPLOYEE WHERE HOBBIES LIKE ‘C%’;
SELECT * FROM EMPLOYEE WHERE ENAME NOT LIKE ‘A%’; OR
SELECT * FROM EMPLOYEE WHERE NOT ENAME LIKE ‘A%’;
SELECT * FROM EMPLOYEE WHERE DESIGNATION LIKE ‘M______’;
ENO EName SAL BONUS Designati Hobbie Gender Addre
SELECT * FROM EMPLOYEE WHERE SAL LIKE ‘7%’; on s s
101 Rohan 2000 100 PEON Cake M SHARJ
SELECTION OF CALCULATED RESULT H
102 Aneeta 3000 200 WORKER Sing F DUBA
SELECT * FROM EMPLOYEE WHERE SAL*12>10000; 103 Pawan 7000 300 MANAGE Dance M SHARJ
Kumar R H
SELECT SAL ,SAL*6 FROM EMPLOYEE ; 104 Rohan 8000 400 MANAGE Sing M DUBA
R
SELECTION FROM A LIST
SELECT * FROM EMPLOYEE WHERE GENDER IN (‘M’,’F’) ; OR
SELECT * FROM EMPLOYEE WHERE GENDER=‘M’ OR GENDER=‘F’;
SELECT * FROM EMPLOYEE WHERE ADDRESS IN (‘SHARJAH’,’DUBAI’);
SELECT NAME ,SAL FROM EMPLOYEE WHERE SAL IN(5000,6000,7000);
40
SELECT * FROM EMPLOYEE WHERE DESIGNATION NOT IN (‘MANANGER’ ,’SALES’,’MP’);
SQL Commands
Roll_n Name Clas Marks City
o s
ORDER BY Clause Chennai
101 Rohan XI 400
ORDER BY clause is used to display the result of a query in a
102 Aneeta XII 390 Bengaluru
specific order(sorted order).
The sorting can be done in ascending or in descending order. 103 Pawan IX 298 Mysore
Kumar
It should be kept in mind that the actual data in the database is
104 Rohan IX 376 Mangalore
not sorted but only the results of the query are displayed in sorted
105 Sanjay VII 240 Mumbai
order.
113 Anju VIII 432 Delhi
e.g. SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student
sorted by name in increasing/ascending order.
41
ARRANGING DATA IN ASCENDING/DESCENDING ORDER - ORDER BY CLAUSE
ENO EName SAL BONUS Designati Hobbie Gender Addres
on s s
101 Rohan 2000 100 PEON Cake M SHARJA
H
102 Aneeta 3000 200 WORKER Sing F DUBAI
103 Pawan 7000 300 MANAGE Dance M SHARJA
Kumar R H
104 Rohan 8000 400 MANAGE Sing M DUBAI
R
• SELECT * FROM EMPLOYEE ORDER BY ENAME;(will display all the details of table in increasing order of ename)
• SELECT * FROM EMPLOYEE ORDER BY SAL DESC; (will display all the details of table in decreasing order of sal)
• SELECT * FROM EMPLOYEE ORDER BY NAME , SAL DESC;(look below for result. Records are arranged
ENO EName SAL BONUS Designati Hobbie Gender Addres
• In increasing order of names.but when two people have on s s
102 Aneeta 3000 200 WORKE Sing F DUBAI
• same name,their records are arranged in desceding R
103 Pawan 7000 300 MANAGE Dance M SHARJA
• Order of sal Kumar R H
104 Rohan 8000 400 MANAGE Sing M DUBAI
R
101 Rohan 2000 100 PEON Cake M 42SHARJA
H
ARRANGING DATA IN ASCENDING/DESCENDING ORDER - ORDER BY CLAUSE
ENO EName SAL BONUS Designati Hobbie Gender Addres
on s s
101 Rohan 2000 100 PEON Cake M SHARJA
H
102 Aneeta 3000 200 WORKER Sing F DUBAI
103 Pawan 7000 300 MANAGE Dance M SHARJA
Kumar R H
104 Rohan 8000 400 MANAGE Sing M DUBAI
R
43
SQL Commands
GROUP BY Clause
The GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the
results by one or more columns.
The syntax for the GROUP BY clause is: Roll_n Name Clas Marks City
o s
SELECT column1, column2, ... column_n, aggregate_function 101 Rohan XI 400 Bengaluru
(expression)
FROM tables 102 Aneeta XII 390 Bengaluru
WHERE conditions 103 Pawan IX 298 Mysore
GROUP BY column1, column2, ... column_n; Kumar
104 Rohan IX 376 Mangalore
e.g SELECT name, COUNT(*) as "Number of employees“ 105 Sanjay VII 240 Mangalore
FROM student WHERE marks>350
GROUP BY city; 113 Anju VIII 432 Delhi
Name Number of employees
Rohan 2
Pawan Kumar 1
Rohan 2
Anju 1 44
AGGREGATE FUNCTIONS
They are functions which work on many tuples and yield one result.Various aggregate functions
are
ENO EName SAL BONUS Design Hobb Gend Addr
• SUM - SELECT SUM(SAL) FROM EMPLOYEE;(20000) ation ies er ess
• AVG – SELECT AVG(SAL) FROM EMPLOYEE;5000 Cake M SHARJ
101 Rohan 2000 100 PEON
AH
• MAX – SELECT MAX(BONUS) FROM EMPLOYEE;400
102 Aneeta 3000 200 WORK Sing F DUBAI
• MIN – SELECT MIN(SAL) FROM EMPLOYEE;2000 ER
• COUNT – This functions counts all non NULL values. 103 Pawan 7000 300 MANA Dance M SHARJ
Kumar GER AH
SELECT COUNT(SAL) FROM EMPLOYEE;4 104 Rohan 8000 400 MANA Sing M DUBAI
• GER
COUNT(*) – This function counts all, even the
• NULL values .
SELECT COUNT(*) FROM EMPLOYEE;4
• 11000 Sing
• SELECT SUM(SAL) , HOBBIES FROM EMPLOYEE GROUP BY HOBBIES HAVING
SUM(SAL)>10000;
• Sum(sal) Hobbies
• 11000 Sing
• SELECT SUM(SAL) , HOBBIES FROM EMPLOYEE GROUP BY HOBBIES HAVING HOBBIES LIKE
‘C%’;
• Sum(sal) Hobbies
• 2000 Cake
NOTE:
• ONLY AGGREGATE FNS AND GROUP BY ATTRIBUTES CAN BE USED IN GROUP BY COMMANDS. 47
• CONDITIONS ARE GIVEN TO GROUP BY STATEMENTS USING HAVING CLAUSE.
Grouping of data - Group by clause
ENO EName SAL BONUS Design Hobb Gend Addr
ation ies er ess
• SELECT SUM(SAL),ADDRESS FROM EMPLOYEE GROUP BY 101 Rohan 2000 100 PEON Cake M SHARJ
ADDRESS ORDER BY SAL; AH
Sum(sal) address
9000 Sharjah
NOTE:
• ONLY AGGREGATE FNS AND GROUP BY ATTRIBUTES CAN BE USED IN GROUP BY COMMANDS.
• CONDITIONS ARE GIVEN TO GROUP BY STATEMENTS USING HAVING CLAUSE. 48
SELECTION USING NULL ENO EName SAL BONUS Design Hobb Gend Addr
ation ies er ess
SELECT * FROM EMPLOYEE WHERE SAL IS NULL;
SELECT * FROM EMPLOYEE WHERE SAL IS NOT 101 Rohan 2000 100 PEON Cake M SHAR
JAH
NULL; OR 102 Aneeta 3000 200 WORK Sing F DUBA
ER I
SELECT * FROM EMPLOYEE WHERE NOT SAL 103 Pawan 7000 300 MANA Dance M SHAR
JAH
Kumar GER
IS NULL; 104 Rohan 8000 400 MANA Sing M DUBA
I
GER
No Name Stipend Stream Avgmark Grade Class • List the names of students who are in grade 12 sorted
s by stipend in ascending order.
50
Unsolved questions
Table 2: INSURANCE • Give the name and type of all companies whose
Company Type Years Name Coverage coverage is more than 100000 but less than 700000.
LIT Life 40 Insured Life policy 200000 • List the different types of policies.
51
Unsolved questions
TABLE 3: ACTIVITY
Acode Activityname Noofparticipa Prizemoney Scheduledate
nts
• To display name of all activities with their
Acodes in descending order.
52
SQL Commands
DELETE Command
To delete the record from a table SQL provides a delete statement.ENO
General
EName
syntax is:-
SAL BONUS Design Hobb Gend
DELETE FROM <table_name> [WHERE <condition>]; ation ies er
e.g. DELETE FROM student WHERE city = ‘Chennai’; 101 Rohan 2000 100 PEON Cake M
This command deletes all those records whose city is Chennai.
102 Aneeta 3000 200 WORK Sing F
ER
103 Pawan 7000 300 MANA Dance M
Kumar GER
54
UPDATE COMMAND
• UPDATE EMPLOYEE SET BONUS=150;
• UPDATE EMPLOYEE SET TAX=100 WHERE TAX IS NULL;
• UPDATE EMPLOYEE SET BONUS=100 ,TAX=10 WHERE EMPNO=12;
• UPDATE EMPLOYEE SET WORKDUR=NULL WHERE ENO=5;
• UPDATE EMPLOYEE SET WORKDUR=10 WHERE ADDRESS =‘SHARJAH’ AND
DEPTNO =‘D001’;
55
SQL Commands
ALTER TABLE Command
In SQL if we ever need to change the structure of the database then ALTER TABLE
command is used. By using this command we can add a column in the existing
table, delete a column from a table or modify columns in a table.
Adding a column
The syntax to add a column is:-
ALTER TABLE table_name
ADD column_name datatype;
Removing a column
ALTER TABLE table_name
DROP COLUMN column_name;
e.g ALTER TABLE Student
DROP COLUMN Address;
The column Address will be removed from the table student
56
ALTER TABLE COMMAND
• ADDING ATTRIBUTES
• DROPPING ATTRIBUTES
57
SQL Commands
If we give command
58
SQL Commands
TABLE : STUDENT
Note that we have just added a column and there will be no data under this attribute.
UPDATE command can be used to supply values / data to this column.
59
SQL Commands
61