SQL
SQL – Structured Query Language :SQL is a simple query
language used for accessing, handling and managing data in
relational databases.
Categorisation of commands
DDL – Data Definition Language
The DDL provides a set of definitions to specify the storage
structure and access methods used by the database system.
Commands covered: Create table, Drop table,Alter table
DML:Data Manipulation Language
A DML is a language that enables users to access or manipulate
data as organized by
Commands covered: Update,Delete,Insert,Select
Terminology
Database :
A database is a collection of interrelated data, and a database
system is basically a computer based record keeping system.
Advantages :
1. Databases reduce the data redundancy (duplication of data) to
a large extent.
2. Database facilitates data sharing.
3. Database provides data security.
4. Database enforces standards.
Terminology :
Relation:
In general, a relation is a table i.e., data is arranged in rows
and columns.
Tuples:
The rows of a relation are known as Tuples.
Attributes:
The columns of a relation are known as Attributes.
Degree:
The number of attributes in a relation is called Degree.
Cardinality:
The number of rows in a relation is known as Cardinality.
Eg
Database: Employee
Relations: Personal,Payslip
Personal
ID Nam Phone Address
e
1 Sam 892892832 12 Vasant Vihar
2
2 Saif 827382276 11/2 Lajpat
3 nagar
Degree:4
Cardinality:2
Attribute: highlighted with Yellow color
Tuple: highlighted in Green color
Payslip
ID Month Amount
1 May 89200
2 May 12300
1 Jun 78000
2 Jun 20000
Degree:3
Cardinality:4
Attribute: highlighted in Yellow color
Tuple: highlighted in green color
a. Basic Commands in MYSQL:
Show databases To list the names of all
databases present
Create database <database To create a database
name>
Eg create database school
Use <database name> To open a database
Eg.
Use school
Show tables To list the names of the
tables in an opened database
b. Create table command (without Constraints): Create table
command is used to create a table in Mysql.
Syntax:
Create table <table name>
(
<field name1> datatype(<size>),
<field name2> datatype(<size>),
<field name3> datatype(<size>),
<field name4> datatype(<size>))
Eg.
Create table report
Regno int(3),
Name char(20),
Dob date,
Stream char(20)
);
Note: Date data type does not need size.
c. Desc command: It is used to describe the structure of the
table. It displays field names, data types and size of each field. It
displays the constraints applied on the fields.
Syntax:
Desc <tablename>
Eg.
Desc report
d. Insert command: Insert command is used to add records in
a table. It has two forms:
Form I:
Syntax:
Insert into <tablename> values(<value1>,<value2>…)
Eg.
Insert into report values(1,’Sam’,’2009-09-19’,’Arts’)
Important:
i. The form of insert can only be used when all fields of the
table are entered and in the same order as they are present.
ii. The char and date values to be enclosed into single or
double quotes.
Form II:
Syntax:
Insert into <tablename>(<fieldname1>,<fieldname2>,…)
values(<value1>,<value2>…)
Eg.
Insert into report(name,stream,dob)
values(’Sam’,’Arts’,’2009-09-19’)
Important:
i. The form of insert can be used when you want to skip a
value for one or more than one field.
ii. The field which is not specified will take a NULL value.
e. Select command:
Select command is used to view the data entered in table/tables.
i. To print all records and all fields
Syntax
SelPect * from <tablename>
Eg
Select * from report ;
ii. To print all records and selective fields
Syntax
Select <column name1>,<column name2> from <tablename>
Eg
Select name,class from report;
iii. To print selective rows: where clause Is used to
restrict the rows by placing a condition.
Syntax
Select * from >tablename> where <fieldname> <condition>
Eg1:
Select name,class from report where name=’Akshay’
Eg2:
Select * from report where agg>=75;
f. Operators in SQL:
i.Relational operators: These operators are used to compare the
values. <,>,>=.<=,!=.=.
Eg:
Select * from report where agg>=75;
ii. Logical operators: These operators are used to combine two
conditions.
And, or and not.
Eg1:
Select * from report where agg>=75 and agg<=90;
Eg2:
Select * from report where name=’Dev’ or name=’Sneha’
iii. Between operator : The operator is used to compare numeric
and date value. It takes lower and upper values and returns the
value within the range . Both the limits are included.
Syntax:
Select <fieldname1>,<fieldname2> from<tablename> where
<fieldname> between lower value and higher value
Eg1:
Select * from report where agg between 75 and 90;
Eg2:
Select * from report where dob between ‘2008-01-01’ and
‘2008-12-31’;
iv. in operator : The operator is used to compare string, numeric
and date values with the list provided in the command
Syntax:
Select <fieldname1>,<fieldname2> from<tablename> where
<fieldname> in (<value1>,<value2>,…)
Eg1:
Select * from report where agg in(60,5,89,45)
Eg2:
Select * from report where dob in(‘2008-01-01’ ,
‘2009-12-21’,’2006-09-11’)
Eg3:
Select * from report where name in(‘Sam’,’Rahim’,’Karam’)
iv. Like operator : The operator is used to match a pattern when
the exact value is not known. It works with two wild card
characters. % stands for none, one or more than one character. _
stands for one and only one character.It works with string and
date values
Syntax:
Select * from<tablename> where <fieldname> like ‘pattern’
Eg1:
Select * from report where name like ‘%s’
(Will Display the details of students whose name is ending with
s)
Eg2:
Select * from report where dob like ‘2008%’
(Will Display the details of students who were born on the year
2008)
Eg3:
Select * from report name like ‘a_’
(Will Display the details of students whose name starts with a
and is exactly two characters long)
g. Multiple Row functions/Aggregate functions /Group
functions: SQL provides with following multiple row functions:
Function name Description
Sum To calculate the sum
Avg To calculate the average
max To calculate the maximum
value
Min To calculate the minimum
value
Count To count the number of not
null entries
Syntax:
Select function(field) from<tablename>
Eg1:
Select max(marks) from student;
Eg2:
Select min(marks),max(marks) from student;
Important:
1. While using these functions in the select command you
cannot display any other field.
2. Multiple aggregate functions can be used in a single
command.
3. The aggregate functions work on multiple rows and return
single output.
4. Where can be used freely while using an aggregate function.
Note: count when used with * will count the complete rows and
when used with a field name will count the entries which are not
NULL.
h. Group by clause: This clause is used to display the aggregate
values group wise.
Eg1:
Select max(marks) from student group by stream;
(will display max marks for each stream individually)
Eg1:
Select stream, max(marks) from student group by stream;
(will display max marks for each stream individually along with
name of the stream)
Important:
1. While using group by clause , its mandatory to have an
aggregate function.
2. The field on which grouping is done can be displayed along
with an aggregate function.
i.having clause: Having clause can be used in two cases:
Case I: When a condition is required to be placed on the field in
which grouping is done.
Eg1:
Select stream, max(marks) from student group by stream having
stream in (‘Sci’,’Arts’)
Case II: When a condition on aggregate value is required to be
placed.
Eg2:
Select stream, max(marks) from student group by stream having
max(agg)>90
Important:
1. Having cannot be used without a group by.
2. It can place conditions either on a group field or on
aggregate function.
3. It is always placed after the group by.
j. Placing text or formula: A text or formula can be placed in a
select command. The text is either enclosed in single or double
quotes, the formula is not enclosed in any quotes.
Syntax:
Select <fieldname1>,’text’,<fieldname 2>,’text’
from<tablename>
Eg1:
Select name,’is on class’,class ,’of section’, section from
student
Eg2:
Select name,agg,agg+agg*.1 from student
k. Working with null: To search for null values an operator is
used .
Eg1:
Select * from student where stream is null;
Eg2:
Select * from student where stream is not null;
l. Arranging data in order: order by clause is used to arrange
data in ascending or descending order. By default, the data is
arranged in ascending order. Desc can be added with a field to
arrange data in descending order.
Eg1:
Select * from student order by name;
Eg2:
Select * from student order by name desc;
Eg3:
Select * from student order by name ,agg desc;
(Data will be arranged in alphabetical order of name and in
case the names are the same it will be arranged in descending
order of aggregate.)
m. Alter table command: This command is used to change the
structure of the table. The command can be use to do
following operations:
i.To add a field:
Syntax:
Alter table <tablename> add <fieldname><data type>(Size)
Eg1:
Alter table student add result char(10)
ii.To modify a field:
Syntax:
Alter table <tablename> modify <fieldname><datatype>(Size)
Eg2:
Alter table student modify result char(20)
iii.To remove a field:
Syntax:
Alter table <tablename> drop <fieldname>
Or
Alter table <tablename> drop column <fieldname>
Eg3:
Alter table student drop result
Or
Alter table student drop column result
i. To change the field name
Syntax:
Alter table <tablename> change <oldfieldname> <new
fieldname> datatype(Size)
Eg4:
Alter table student change result status char(20)
ii. To change the table name
Syntax:
Alter table <tablename> rename <newtablename>
Eg5:
Alter table report rename reportcard
n. Update command: This command is used to modify the data
stored in a table. If the command is executed without a
condition all the records will be modified.
Syntax:
Update <tablename> set <fieldname>=value
Eg1:
Update student set agg=agg+agg*.1
(Every student’s aggregate will increase by 10%)
Eg2:
Update student set stream=’Science’ where name=’Amit’
(Amit will be allotted science stream)
Eg3:
Update student set stream=’Science’,section=’A’, class=’XII’
where name=’Amit’
(Amit will be allotted science stream, section A and class XII)
o. Delete command: This command is used to remove rows of
a table. If executed without condition all the rows will be
deleted.
Syntax:
Delete from <tablename>
Eg1:
Delete from student
(All the rows from student will be deleted)
Delete from <tablename> where <fieldname> condition
Eg2:
Delete from student where agg<33
(Records of Students with aggregate less than 33 will be
removed)
Important:Delete command only deletes records of the table.
The structure of table remains intact)
o. Drop table command: This command is used to remove the
structure of the table. This Command removed the complete
structure with data. Once the table is deleted it cannot be
restored.
Syntax:
Drop table <tablename>
Eg:
Drop table student;
Concept of Keys
Domain: This refers to the pool from which actual value appears. For eg. regno of
a student table may be drawn from a domain of valid regno assigned in a table.
Personal Table
Regno Name DOB
1011 Amit 2002-01-12
1022 Kabir 2003-03-19
1033 Simon 2003-12-18
1044 Kiran 2002-11-23
The values specified in the circle are the values from which the Regno of
examination table will withdraw its data. This area is known as domain
Examination Table
Regno Term Marks
1011 1 90
1022 1 45
1033 2 89
1044 1 43
1011 2 78
Keys
Primary Key: A primary key is a set of one or more attributes that can uniquely
identify tuples within a relation.
Candidate Key: All the attributes(column/field) of a table which can serve as
primary key.
Alternate Key: A candidate key that is not a primary key is termed as alternate
key.
Constraints in SQL
The constraints are the restrictions which are applied to a field or group of fields
to ensure validity of data. The constraints can be applied during creation of table,
while using create table command or after creation of table using Alter table
command.
SQL constraints
1. Not Null: Ensures that column cannot have null values.
2. Default: Provides a default value for a column when none is
specified.
3. Unique: Ensures the values of field are not repeated. They
are different.
4. Check: Ensures the value of field satisfies criteria
5. Primary Key: Uniquely identifies a row
6. Foreign Key: Ensures referential integrity
Table :DATA
Field Name Description Constraint
Adhar_card Adhar no of person Primary Key
Passport_no Passport number of Will be unique
person
Pan_no Pan number of Will be unique
person
Name Name of person Can’t be left blank
DOB Date of birth Must be greater
than or equal to 1
January , 2001
Driving_lice Driving license Will be unique
nse number of person
Age Age of person Must be greater
than or equal to 18
City City of person Default value ‘
delhi’
Create table Data(
Adhar_card char(10) primary key,
Passport_no char(15) unique,
Pan_no char(15) unique,
Name char(20) not null,
Dob date check(dob>=’2001-01-01’),
Driving_licence char(20) unique,
Age int(2) check(age>=18),
City char(20) default “delhi”));
Please Note and read following description twice after going through above
command:
1. Primary key and Unique both ensure that the field cannot have duplicate
values. The difference is Primary key constraint can be applied only once and
unique constraint can be applied multiple times in table.
Types of level of constraints
Constraints can be applied at two level in sql,
1. Field level Constraint: This constraint involves only one field of the table. These
constraints are specified next to the field of the table.
Create table Data(
Adhar_card char(10) primary key,
Passport_no char(15) unique,
Pan_no char(15) unique,
Name char(20) not null,
Dob date check(dob>=’2001-01-01’),
Driving_licence char(20) unique,
Age int(2) check(age>=18),
City char(20) default “delhi”));
Concept of Keys
Domain: This refers to the pool from which actual value appears. For eg. regno of
a student table may be drawn from a domain of valid regno assigned in a table.
Personal Table
Regno Name DOB
1011 Amit 2002-01-12
1022 Kabir 2003-03-19
1033 Simon 2003-12-18
1044 Kiran 2002-11-23
The values specified in circle, are the values from which Regno of examination
table will withdraw its data. This area is known as domain
Examination Table
Regno Term Marks
1011 1 90
1022 1 45
1033 2 89
1044 1 43
1011 2 78
Keys
Primary Key: A primary key is a set of one or more attributes that can uniquely
identify tuples within a relation.
Candidate Key: All the attributes(column/field) of a table which can serve as
primary key.
Alternate Key: A candidate key that is not a primary key is termed as alternate
key.
Constraints in SQL
The constraints are the restrictions which are applied to a field or group of fields
to ensure validity of data. The constraints can be applied during creation of table,
while using create table command or after creation of table using Alter table
command.
SQL constraints
1. Not Null: Ensures that column cannot have null values.
2. Default: Provides a default value for a column when none is
specified.
3. Unique: Ensures the values of field are not repeated. They
are different.
4. Check: Ensures the value of field satisfies criteria
5. Primary Key: Uniquely identifies a row
6. Foreign Key: Ensures referential integrity
Table :DATA
Field Name Description Constraint
Adhar_card Adhar no of person Primary Key
Passport_no Passport number of Will be unique
person
Pan_no Pan number of Will be unique
person
Name Name of person Can’t be left blank
DOB Date of birth Must be greater
than or equal to 1
January , 2001
Driving_lice Driving license Will be unique
nse number of person
Age Age of person Must be greater
than or equal to 18
City City of person Default value ‘
delhi’
Create table Data(
Adhar_card char(10) primary key,
Passport_no char(15) unique,
Pan_no char(15) unique,
Name char(20) not null,
Dob date check(dob>=’2001-01-01’),
Driving_licence char(20) unique,
Age int(2) check(age>=18),
City char(20) default “delhi”));
Please Note and read following description twice after going through above
command:
1. Primary key and Unique both ensure that filed cannot have duplicate
values. The difference is Primary key constraint can be applied only once and
unique constraint can be applied multiple times in table.
Foreign Key Constraint
Foreign Key constraint ensures referential integrity. Referential integrity is a
system of rules that a DBMS uses to ensure that relationship between records of
related table are valid , and that users don not accidentally delete or change data.
All the cases have been explained while discussion of foreign key. Please refer to
that part.
Defining Foreign Key: A field is eligible to be foreign key in a table , if and only if
it is primary kay in the related table .
Personal Table
Regno(Primary Name DOB
Key)
1011 Amit 2002-01-12
1022 Kabir 2003-03-19
1033 Simon 2003-12-18
1044 Kiran 2002-11-23
Examination Table
Regno(Foreign Term Marks
Key)
1011 1 90
1022 1 45
1033 2 89
1044 1 43
1011 2 78
1024 1 78
Create table personal(Regno int(4) Primary Key,name char(20),dob date)
Create table examination
(regno int(4),
Term int(1),
Marks float(3),
Foreign key (Regno) references personal(regno));
Please Note:
1. Regno is primary key in personal table, so eligible to be
foreign key.
2. The foreign key constraint is given after the last field of
examination table after placing a comma.
3. References,foreign ,key are reserve words.
4. The name of the field is enclosed in round brackets () which
is mandatory.
5. Last but most important, it is not mandatory that the field
name Regno has to be same in both tables. The primary key can
be named as regno in personal table and Enrrollment_no in
examination. The data type must match in both.
Create table personal(Regno int(4) Primary Key,name
char(20),dob date)
Create table examination
(enrollment_no int(4),
Term int(1),
Marks float(3),
Foreign key (enrollment_no) references personal(regno));
Personal Table
Regno Name DOB
1011 Amit 2002-01-12
1022 Kabir 2003-03-19
1033 Simon 2003-12-18
1044 Kiran 2002-11-23
The values specified in circle, are the values from which Regno
of examination table will withdraw its data. This area is known as
domain
Examination Table
Regno Term Marks
1011 1 90
1022 1 45
1033 2 89
1044 1 43
1011 2 78
Foreign Key: A non-key attribute whose values are derived from primary key of
some other table.
Personal Table
Regno(Primary Name DOB
Key)
1011 Amit 2002-01-12
1022 Kabir 2003-03-19
1033 Simon 2003-12-18
1044 Kiran 2002-11-23
Examination Table
Regno(Foreign Term Marks
Key)
1011 1 90
1022 1 45
1033 2 89
1044 1 43
1011 2 78
· Regno of examination table cannot contain a value which is
not present in Personal Table.
· Non-Key means it can’t be used to identify a row/tuple of table.
· The Regno of personal table identifies a row. Eg. 1033 will exist
only once in personal table and it refers to simon’s record. Regno
is a key attribute in personal table but a non-key in
examination table.
What will foreign key ensures? Please carefully check the records of personal
and examination table.
1.Will allow the foreign key field to have any value unless and until its present in
Personal table
Insert into examination values(1024,1,45);, will flag an error as 1024 is not present
in personal table.
Regno(Foreign Term Marks
Key)
1011 1 90
1024 1 45
1033 2 89
1044 1 43
1011 2 78
Second entry(marked as red ) won’t be allowed because Personal table does not
contain 1024 as Regno.
2. If user tries to change regno from 1011 to 1012 in personal table. The update
command will flag an error because examination table contains 1011.
Update personal set regno=1012 where regno=1011, will flag an error.
Personal Table
Regno(Primary Name DOB
Key)
1011 Amit 2002-01-12
1022 Kabir 2003-03-19
1033 Simon 2003-12-18
1044 Kiran 2002-11-23
Examination Table
Regno(Foreign Term Marks
Key)
1011 1 90
1022 1 45
1033 2 89
1044 1 43
1011 2 78
3. If user tries to delete record of a student with regno 1011 from personal table
The delete command will flag an error.
Delete from personal where regno=1011;, will flag an error because examination
table contains 1011.
Personal Table
Regno(Primary Name DOB
Key)
1011 Amit 2002-01-12
1022 Kabir 2003-03-19
1033 Simon 2003-12-18
1044 Kiran 2002-11-23
Examination Table
Regno(Foreign Term Marks
Key)
1011 1 90
1022 1 45
1033 2 89
1044 1 43
1011 2 78
The creation of foreign key ensures that data in two connected
table is valid.
Working with multiple tables:
Sql provides us the option to extract data from more than one table. Before we
start learning about extraction of data. Lets look at JOINS.
A join is a query that combines rows from two or more tables. In a join query
more than one table name is listed with FROM clause. The operation of
combining data of multiple tables is termed as joining.
Few commonly joins in SQL
1. Cross join
2. Equi join
3. Natural Join
Cross Join: A sql query without any join condition generates cartesian product
.This means each record of first table is combined with each record of second
table. For eg if table1 contains 10 records and table2 cobtains 5 records ….
Select * from table1,table2;
The above command is trying to retrieve records from table1 and table2. This
command will yield 50 rows ie 10 X5=50
Personal Table
Regno(Primary Key) Name
1011 Amit
1022 Kabir
1033 Simon
Examination Table
Regno(Foreign Key) Term Marks
1011 1 90
1022 1 45
1033 2 89
1011 2 78
1022 1 34
1033 1 60
Personal table =3 records/rows
Examination = 6 records.
Select * from personal ,examination;
Output=18 records
Giving a sample of output
Regno Name Regno Term Marks
1011 Amit 1011 1 90
1011 Amit 1022 1 45
1011 Amit 1033 2 89
1011 Amit 1011 2 78
1011 Amit 1022 1 34
1011 Amit 1033 1 60
1022 Kabir 1011 1 90
1022 Kabir 1022 1 45
1022 Kabir 1033 2 89
1022 Kabir 1011 2 78
1022 Kabir 1022 1 34
1022 Kabir 1033 1 60
1033 Simon 1011 1 90
1033 Simon 1022 1 45
1033 Simon 1033 2 89
1033 Simon 1011 2 78
1033 Simon 1022 1 34
1033 Simon 1033 1 60
Please check each record of personal is combined with each row of examination
table.
The statement: Select * from personal ,examination; creates what we called in SQL a
cross join. The output obtained is not a valid output.
Equi Join: The join, in which column are compared for equality.
Lets look at these three situations for given below tables:
Personal Table
Regno(Primary Key) Name
1011 Amit
1022 Kabir
1033 Simon
Examination Table
Regno(Foreign Key) Term Marks
1011 1 90
1022 1 45
1033 2 89
1011 2 78
1022 1 34
1033 1 60
Situation I: Display name and marks of all students
Select name,marks from personal,examination where
personal.regno=examination.regno;
The command will pick name from personal table and marks from examination
table. It will compare the regno of personal table with regno of examination table.
If the value matches th the record will be shown.
Name Marks
Amit 90
Amit 78
Kabir 45
Kabir 34
Simon 89
Simon 60
The condition personal.rego=examination.regno is known as equi join.
Situation II: Display name ,Term , marks of those students who are scoring marks
less than 50.
Select name,term ,marks from personal, examination where
examination.regno=personal.regno and marks<50
Or
Select name,term ,marks from personal, examination where marks<50 and
examination.regno=personal.regno
Name Term Marks
Kabir 1 45
Kabir 1 34
Situation III: Display name and marks for second term.
Select name, marks from personal, examination where
examination.regno=personal.regno and term=2
Or
Select name, marks from personal, examination where term=2 and
examination.regno=personal.regno;
Name Marks
Simon 89
Amit 78
Natural Join:
It is a type of equi join in which an identical column is not
repeated in the output.
Select * from vehicle, challan where vehicle.regno=challan.regno;
The above command is an example of equi join, Where regno of
vehicle will be displayed twice. Once from each table.
Select * from vehicle natural join challan;
Will give the same number of rows and one less column. The
Regno will be displayed only once.
Eg. Display all the details from both tables who were challaned in
the month of April.
Select * from vehicle natural join challan where date_offence like
‘%-04-%’
Or
Select * from challan natural join vehicle where date_offence like
‘%-04-%’