SlideShare a Scribd company logo
1 of 50
INTRODUCTION
DBMS(Database Management System) is a collectionof inter-
related programs that enable users to create, maintain database
and control all the accesses to the database .Database is needed
to develop the software so that multiple users can access the
data.
The basic processes that are supported by DBMS are:-
 Storing the data.
 Manipulation of database.
 Querying the databaseto retrieve desired data.
 Updating the content of database.
Early InformationSystem
When DBMS was not there in early times so peopleused early
information system. Early information system used operating
system to perform several operations.
Problems
DisorganizedDevelopment
Application
Programs
File
System
Disk
When peopleused to make their own programs then nobody
knew what others have donedue to that data used to become
redundant as peoplecould not access otherprograms.
Data Isolation
There was inconsistency in the programs. As multiple users
used to design their own programs sitting at multiple places
around the world.
Modern Problems
There was concurrencyin the system as many peopleused to
updatesame information at same moment of time.
Integrity Constraints
There were no constraintsin such system.
How Databaseis organized?
Data itself need to be stored in a standard way so that database
can retrieve and can manipulateit. There are no. of levels at
which we can look at the storage of data.
Some keywords involved in this process are:-
Fig: DATABASE HIERARCHY
Role of DBMS
DATABASE FILE
TABLE
FIELD
DATA TYPE
VALUE
DATABASE FILE:-
Applicationprograms
DBMS
OPERATING
SYSTEM
DISK OR ACTUAL
DATABASE
This is your main file that encompasses the entire database. For
example, school, bank, etc and that is saved to your hard drive or
floppy disk or pen drive.
TABLE:-
A tableis a collection of data related to a single topic and a
database is a collection of tables. For example a school database
may comprise a no. of tables such as teacher personal details,
teacher salary data, student details, student mark sheet etc.
Note that each table is related to a single topic while a database
is related to multiple tables.
RECORDS:-
Record is the information related to one entity. A tableis made
up of a no. of rows or records. In our example each record or row
of teacher personal details tablewould contain data of a specific
teacher or a student details table would contain data on a specific
student.
FIELDS:-
Field is the individual sub componentof one record. Each
database tableis partitioned into one or more fields. Fields are
different categories within a table. Example roll_no, name, dob,
address, etc.
The FIELD NAME is a program variable associated with this
field. This name should be meaningful and a single token (no
blanks).
DATA TYPES:-
Data types are the propertiesof each field. For example roll_no
as number, name as text, dob as date etc.
A tablecan have up to 254 columns which may have different or
same data types and sets of values (domains), respectively.
Possible domains are alphanumeric data (strings), numbers and
date formats.
Oracle offers the following basic data types:
_ char(n): Fixed-length characterdata (string), n characters
long. The maximum size for n is 255 bytes (2000 in
Oracle8). Note that a string of type char is always padded on
right with blanks to full length of n.
Example: char(40)
_ varchar2(n):Variable-length characterstring. The
maximum size for n is 2000 (4000 in Oracle8). Only the
bytes used for a string require storage. Example:
varchar2(80)
_ number(o; d): Numeric data type for integers and reals. o
= overall number of digits, d = number of digits to the right
of the decimal point.
Maximum values: o =38, d= �84 to +127. Examples:
number(8), number(5,2)
Note that, e.g., number(5,2)cannot contain anything larger than
999.99without resulting in an error.
Data types derived from number are int[eger], dec[imal], smallint
and real.
_ date: Date data type for storing date and time.
The default format for a date is: DD-MMM-YY. Examples: '13-
OCT-94', '07-JAN-98'
_ long: Characterdata up to a length of 2GB. Only one long
column is allowed per table.
Let us take an example of student table with followingdata in
a relational databasefor a school:-
Roll_no Name Dob Address
Number Character Date Character
1001 Ridhi Narang 1996-04-07 56/18 Kamla
nagar
1002 Ananay
Narang
2001-02-02 56/19 kamla
nagar
1003 Aditi Narang 1998-08-11 56/19 kamla
nagar
1004 Pushkar
Narang
1994-06-17 56/18 kamla
nagar
The student tablehas four columns and four rows. The data types
for a column indicate the type of data that may be stored in that
column.
 Field name:- Roll_no, Name, Dob, Address.
 Data type:- Number, Character, Date.
Structured query language(SQL)
SQL is a special-purpose programming
language designed for managing data held in a relational
database management system (RDBMS), or for stream
processing in a relational data stream management
system (RDSMS).
Originally based upon relational algebra and tuple
relational calculus, SQL consists of a data definition
language and a data manipulation language. The scope of
SQL includes data insert, query, update and
delete, schema creation and modification, and data access
control. Although SQL is often described as, and to a great
extent is, a declarative language (4GL), it also includes
procedural elements.
SQL was one of the first commercial languages for Edgar
F. Codd's relational model, as described in his influential
1970 paper, "A Relational Model of Data for Large Shared
Data Banks."Despite not entirely adhering to the relational
model as described by Codd, it became the most widely
used database language.
SQL became a standard of the American National
Standards Institute (ANSI) in 1986, and of the International
Organization for Standardization (ISO) in 1987. Since then,
the standard has been revised to include a larger set of
features. Despite the existence of such standards, though,
most SQL code is not completely portable among different
database systems without adjustments.
History
SQL was initially developed at IBM by Donald D.
Chamberlin and Raymond F. Boyce in the early
1970s. This version, initially called SEQUEL (Structured
English Query Language), was designed to manipulate and
retrieve data stored in IBM's original quasi-relational
database management system, System R, which a group
at IBM San Jose Research Laboratory had developed
during the 1970s. The acronym SEQUEL was later
changed to SQL because "SEQUEL" was a trademark of
the UK-based Hawker Siddeley aircraft company.
In the late 1970s, Relational Software, Inc. (now Oracle
Corporation) saw the potential of the concepts described
by Codd, Chamberlin, and Boyce, and developed their own
SQL-based RDBMS with aspirations of selling it to the U.S.
Navy, Central Intelligence Agency, and other U.S.
government agencies. In June 1979, Relational Software,
Inc. introduced the first commercially available
implementation of SQL, Oracle V2 (Version2)
for VAX computers.
After testing SQL at customer test sites to determine the
usefulness and practicality of the system, IBM began
developing commercial products based on their System R
prototype including System/38, SQL/DS, and DB2, which
were commercially available in 1979, 1981, and 1983,
respectively.
Classificationof SQL statements
1.Data definitionlanguage (DDL):-Thesestatements are used to
create and modify the structureof your tables. When you execute
a DDL statement, it takes effect immediately.
Eg. CREATE TABLE, ALTER TABLE, DROP TABLE etc.
2.Data manipulation language (DML):-These statements are
used to manipulatethe data base objects. By data manipulation
we mean:-
 The RETRIEVAL of information stored in database.
 The INSERTION of new information into database.
 The DELETION of information from the database.
 The MODIFICATION of data stored in database.
Eg. SELECT, INSERT, DELETE, UPDATE etc.
The DMLs are basically of two types:-
ProceduralDMLs require a user to specify what data is needed
and how to get it.
Non procedural require a user to specify what data is needed
without specifying how to get it.
3. Utilitystatement:-DESCRIBE, EXPLAIN, HELP etc.
4. Database control language (DCL):- These statements are used
for database administration.
Eg. GRANT, DENY, REVOKE etc.
5. Locking and transactional statements:-
Eg. LOCK TABLES, UNLOCK TABLES, COMMIT, ROLL
BACK etc.
DMLs
Procedural
Non-
Procedural
CASE SENSTIVITY IN SQL STATEMENTS
A case sensitivity rule in SQL statements vary for different part
of statements and also dependson what you are referring to and
the OS of the machine the server is running:-
 SQL Keywords and FunctionNames
Keywords and function names are not case sensitive.They can be
given in any lettercase.
Eg.
Select now( );
Select NOW( );
Select Now( );
Theses all statement will execute and producethe same
results.
 Column and index names
Column and index names are not case sensitive in SQL.
Eg.
Select name from teacher;
Select NAME from teacher;
Select Name from teacher;
 Alias names
Aliases are case sensitive. We can specify an alias in any
lettercase, but we must refer to it elsewhere in the query
using the same case.
Comments in SQL
Comments can be useful for documentingQueries that you store
in files.
There are two recommended comment styles.
 First, anything from a ’#’ character to the end of a line is
considered a comment.
Eg.
#This is a single line comment
 Second, C-style comments are allowed as well. That is
anything between the ‘/*’ and ‘/*’ beginning and ending
markers is considered a comment.
Eg.
/* This is also a single line comment */
/* This , however ,
is a multipleline
comment*/
DATA TYPES OF SQL
A datatypein a programming language is a set of data with
values having predefined characteristics.
1.INTEGER
TYPE SIZE
INT 4 bytes
SMALLINT 2 bytes
MEDIUMINT 3 bytes
BIGINT 8 bytes
TINYINT 1 byte
2.FLOAT
It is a small number with a floating decimal point.
It’s size is 4 bytes.
3.TEXT/STRINGTYPES
TYPE SIZE DESCRIPTION
CHAR Length bytes A fixed length field
from 0 to 255
characters long.
VARCHAR String length + 1
bytes
A fixed length field
from 0 to 255
characters long.
TINYTEXT String length + 1
bytes
A string with max
length of 255
characters.
TEXT String length + 2
bytes
A string with max
length of 65535
characters.
MEDIUMTEXT String length + 3
bytes
A string with max
length of 16777215
characters.
LONGTEXT String length + 4
bytes
A string with max
length of
4294967295
characters.
4.DATE TYPES
TYPE SIZE DESCRIPTION
DATE 3 bytes In the format of YYYY-
MM-DD
DATETIME 8 bytes In the format of YYYY-
MM-DD HH:MM:SS
TIMESTAMP 4 bytes In the format of
YYYYMMDDHHMMSS
; acceptablerange ends in
the year 2037
TIME 3 bytes In the format of
HH:MM:SS
HOW TO CHOOSE YOUR DATA TYPE
 Identify whether a column should be a text, number, or data
type.
 Choose the most appropriatesubtypefor each column.
 Set the maximum length for text and number columns as
well as attributes.
OPERATORS IN SQL
Operators are componentsof expressions to specify the
interactionsand conditionsthat affect and limit the range of
values in a result set.
OPERATOR PRECEDENCE
Highest precedence :=
1 OR, XOR, ||
2 &&, AND
3 BETWEEN, CASE,WHEN,
THEN, ELSE
4 =,<=, >=, <, >, IS, LIKE, IN
5 |
6 &
7 <<, >>
8 -,+
9 *,%, /
10 ^
11 -(UNARY MINUS),
~(UNARY BIT INVERSION)
12 !, NOT
Lowest BINARY COLATE
ARITHMETIC OPERATORS:-These operatorsare used to
perform mathematical calculations.
OPERATOR DESCRIPTION
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
COMPARISON OPERATORS:-These are also called as relation
operators. These are used for comparison purposes.
OPERATORS DESCRIPTION
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
!= Not equal to
BOOLEAN/LOGICAL OPERATORS:- These operatorsare
either true or false.
OPERATORS DESCRIPTION
AND Return T if both inputs are
T
OR Return T if any one of the
input is T
NOT Change the input from T to
F or from F to T
SQL WORD OPERATORS:-
OPERATOR DESCRIPTION
BETWEEN Returns values in given
range i.e. in b/w the inputs
IN Returns values in specified
subset
LIKE Return values that matches
a simple pattern
NOT Negates an operation means
opposite
CONSTRAINTS
 Not null:-It ensures that we cannot leave a column as null Eg.
Name is always mandatory.
 Default:-It prevents null from occurring if a row is inserted
without a value for the column.
 Check:-It defines a condition that each row must satisfy.
KEYS
KEYS
PRIMARY
ALTERNA
TE
CANDIDATE
FOREIGN
 Primary key:-It helps us to uniquelyidentifies each row in table.
It can neitherbe normal attributei.e. guaranteed to be
unique(suchas SSN in a tablewith no more than one record per
person) or it can be generated by DBMS(such as a globally
uniqueidentifier).
Based on the primary key the database system ensures that no
duplicationappearin the table.
To choose a primary key for an entity must have following
properties:-
 The values must not change or become null during the life of
each entity.
This table shows some of the primary key fields which
uniquelyidentify the tableto make relation with another
table.
TABLE NAME PRIMARY KEY
ATTRIBUTE
STUDENT ROLL_NO
CUSTOMER CUST_ID
TEACHER TNO
DEPARTMENT DEPT_NO
EMP EMP_NO
DEPT DEPT_NO
 Foreign key:-It is declared as primary key in othertable and
used to enforce referential integrity. It identifies a column or set a
column in one table that refers to a column or set of columns in
anothertable. The columns in the referencing tablemust be the
primary key or other candidatekey in the referenced table. A
table may have multiple foreign keys.
Primary keys and foreign keys in table
Primary key
Foreignkey
TEACHER
TNO
TADDRESS
SALARY
DEPT_NO
DOJ
DEPARTMENT
DEPT_NO
DEPT_NAME
 Candidatekey:-It is one that can identify each row of a table
uniquely. Generally, a candidatekey becomes the primary key of
the table.
There are three fundamental demands on the candidatekeys that
we should never deviate from:-
 It must be unique.
 It cannot hold NULLs.
 It should never change i.e. should hold the same value during
its lifetime.
E.g. SSN, E_ID, D_NO, etc.
 Alternate keys:-If tablehas more than one candidatekey, then
one is called primary key and rest are called Alternative keys.
Let us take an example of our class. Supposein our class we
have to select our class monitor. So A, B, C and D stand for that
post. So A, B, C and D are candidatefor monitor so these are
candidatekeys. We select B as a monitor so B is a primary key
and A, C and can be monitor but not selected as a monitor so
they are alternative choice and are called alternative keys.
TABLE/COLUMNNAMING CONVENTIONS
The table-name/field/column can be assigned according to the
following rules:-
 A name will start with either a letter or from an underscore.
 After the first characterwe can use any combination of
letters, digits, or underscore.
 A name will not start with two underscores.
 A name will not include one or more empty spaces. i.e. a
name will be made in one word.
 If the name is combination of words, each word part will
start in uppercase.
E.g. DateHired, DriversLicenseNumber etc.
SOME SQL COMMANDS
CREATE:-This command is used to create the tables.
The creation commands requires:-
 Name of the table
 Name of fields
 Definations for each field.
The syntax for creating a table is:
Create table<table_name >( Field1 data type, field2 type,
etc……….);
Example
Create table teacher (tno varchar (4) primary key not null,
tname char(25), taddress varchar(30),salaryfloat, dept_no
char(4), doj date);
In this way teacher tableis created.
DESCRIBE:-This command is used to describe the structureof
our table
It is used to show the attributesof the tablewith the constraint
NULL/NOT NULL.
DESCRIBEteacher;
Output is
FIELD TYPE NULL KEY DEFAULT
Tno Varchar(4) No Pri
Tname Varchar(25) Yes Null
Taddress Varchar(25) Yes Null
Salary Float Yes Null
Dept_no Char(4) Yes Null
Doj Date Yes Null
INSERTINGDATA:-
Insert command is used to insert new rows in a table. It is a DML
command. Data manipulationcapabilities allow one to retrieve
and modify the contentsof the table.
The syntax for insert statement is:-
Insert into<table_name> values( value1, value2,etc……..);
Insert into teacher values (‘t01’,’rakeshsharma’,’245
malviya nagar’, 25600,’d05’,’2012-12-12’);
This is how we insert values.
SELECT:-It is used to retrieve the information from the tables.
 The select list must include atleast one column name or one
expression. If more than one column or expression element
is included, they must be separated by a comma.
 We can assign an alias to a column name or expression.
 Although the select clause is the only required element in a
select statement you cannot retrieve data from a table unless
you also specify a FROM clause.
FROM CLAUSE:-It specifies the tables that are used to retrieve
values. This clause is followed by a space and then the name of
database being used as a source of information.
Retrievingall the columns:-
If you want to see every column of table the astrerisk(*) is a
convenient short hand that means all column.
WHERECLAUSE:-It specifies the condition either it would be
true or false. It specifies the search condition used to determine
the data that will appear in the result table. The syntax is
Select column name1, column name2……..fromtable name
[where condition];
The square bracket in where clause means that the clause is
optionali.e. you can use select statement without using this
clause.
The where clause expects three elements:-
 Column name
 Comparison operator
 Column name, constantsor list of values
The where clause goes through the entire table one row at a time
and examines each row to determine if the condition is true or
false. As you can see a where clause must contain atleast one
expression that defines which rows the select statement returns.
When you specify more than one condition in where clause,
those condition are connected by an AND or an OR operator.The
operatorsspecify which conditionor combination of conditions
must be met.
Select *from teacher;
This would display all the result i.e. the complete teachertable.
TNO TNAME TADDRESS SALARY DEPT_NO DOJ
T01 RAKESH 245
MALVIYA
NAGAR
25600 D05 2001-
12-12
T02 JUGAL
MITTAL
34,RAMESH
NAGAR
22000 D02 1999-
07-03
T03 SHARMILA D-31
ASHOK
VIHAR
21000 D01 2000-
06-06
T04 SANGEETA G-35
MALVIYA
NAGAR
18900 D05 2000-
02-20
T05 SHIV OM R-44 KIRTI
NAGAR
13000 D02 2001-
09-22
T06 RAMESH B-42
SHALIMAR
BAGH
24000 D03 1997-
07-03
T07 VIVEK E-33
ROHINI
WEST
12000 D01 2001-
10-12
RETRIEVING FROM SPECIFIC COLUMN
1. Select tno, tname, salaryfrom teacher;
This would display tno, tname, salary from teacher table.
2. Select tno, tname, salaryfrom teacher where tno=T06;
This would give details of T06 as his tno i.e. of ramesh.
3. Select tno, tname from teacher where tname like’R%’;
This would give details of Rakesh and Ramesh.
LIMIT CLAUSE:-It is used to limit the no. of rows. It takes 2
arguments i.e. from where to start and upto what extent it should
proceed.
Select * from teacher LIMIT 2,5;
It would display result as all the details of T03 uptoT07.
Tno Tname Taddress Salary Dept_no Doj
T03 SHARMILA d-31
ashok
vihar
21000 D01 2000-
06-06
T04 SANGEETA g-35
malviya
nagar
18900 D05 2000-
02-20
T05 SHIV OM r-44 kirti
nagar
13000 D02 2001-
09-22
T06 RAMESH b-42
shalimar
bagh
24000 D03 1997-
07-03
T07 VIVEK e-33
rohini
west
17000 D01 2001-
10-12
UPDATINGTABLE
This is used to modify existing data in the table.
The basic syntax for UPDATE statement is:-
UPDATE tableset field=value [, field=value][where conditions];
The UPDATE is followed by a tablename and sat clause with pair
of column names and associated expressions that are being
assigned to the column.
Eg.
Update teacher set tname=RAMU where tname=Ramesh;
It would make changes in tableas ramesh would be modified to
RAMU.
Using expressionin UPDATE
Scalar expression can be used in UPDATE command i.e. we can
also set all the rows of particularcolumn wth a single value.
Eg.
UPDATEteacher set salary =salary+500 where salary<15000.
Result is
Tno Tname Taddress Salary Dept_no Doj
T05 Shivam
om
r-44,kirti
nagar
13500 D02 2001-09-
22
Updatingwith multiple columns
We can updatemore than 1 column using UPDATE command.
Eg.
UPDATE teacherset tname=’john Roy ’ , dept_no=’D03’where
tname =’shiv om’;
Result would be
It will replace shiv om to john roy.
ALTER TABLE
It allows you to make changes in the existing table in many
ways such as :-
1.Adding column:- This would help us to add new column.
Alter table teacher add column age int after salary;
Result would be a new column named as AGE would be
added after salary column.
2.Adding constraint:- This would help us to add constraint
such as not null , primary key etc.
Alter table teacher modify tname varchar(10)not
null; It would make the changes in the existing table.
ORDERINGTHE DATABASE
It determines the order of rows in the result tablei.e. either in
ASC or DESC.
By default order is ASC.
Select * from teacher order by salary;
This would display all the details along with salary in ascending
order
DELETE STATEMENT
It deletes the rows from table and returns the no. of rows deleted.
DELETE from teacher;
It would delete all the rows.
DELETE from teacher where tno=’T01’;
It would delete only a particularrow i.e. T01.
DROP TABLE
It would delete the whole table.
DROP TABLE teacher;
Result would be that now no teachertable exists.
COUNTFUNCTION
It is used to count the no. of values in a given column, or no. of
rows in the table.
Select count(*) from teacher;
Result is 7
As it countsthe total no. of teachers in the teacher table.
DISTINCT CLAUSE
It is used to extract uniquethings from the table.
The syntax of distinct clause is:-
Select DISTINCT column name from tablename;
Select count( distinctdept_no) from teacher;
Result is 4
Select distinct count(dept_no)fropmteacher;
This query doesn’t work accordingly as distinct dept_no would
not be countedall the rows would be counted.
LIKE CLAUSE
The LIKE operatoris used to check if field values match a
specified pattern, and searches for less-than-exact but similar
values. LIKE can be applied to only CHAR and VARCHAR
fields. The LIKE searches a characterfield to see if part of it
matches a string. The LIKE clause is used to select rows which
are matching wildcards patterns. Note that the patternsare case
sensitivity i.e. the uppercase letters do not match lower case
letters.
The syntax is as:
Select column name1, column name2,……
From table name
Where column name like ’%’;
QS:- Write a query to display teacherno and teachername whose
name started with alphabet ‘R’.
Select tno, tname from teacher where tname like ‘R%’;
Tno Tname
T01 Rakesh Sharma
T06 Ramesh kumar
ALL CLAUSE
The ALL clause is same as that when you do not specify
DISTINCT. The ALL clause retains the duplicaterows.
The syntax is as:
Select ALL column name
from table name;
Select ALL tname from teacher;
BETWEEN CLAUSE
The BETWEEN operatoris used to check if field values are
within a specified inclusive range BETWEEN is sensitive to
order, and the first value in the clause must be in alphabeticor
numeric order.
The syntax is as:
Select column name1, column name2,…..
from tablename
where column name between value1 and value2;
QS:- Write a query to display teacherno, teacher name and salary
of all the teachers whose salary is between 15000AND 20000.
Select tno, tname, salary
from teacher
where salary between 15000AND 20000;
Tno Tname salary
T04 Sangeeta 18900
IN CLAUSE
The IN clause is used to specify condition based on a list. The IN
operatorselects values that match any value present in the list of
values.
The syntax is:
Select column name1, column name2,….
From table name
where column name IN ( value1,value2,……,valuen);
QS:- Write a query to display teacherno, teacher name and salary
of the teachers t01,t02and t03.
Select tno, tname, salary
from teacher
where tno IN(‘t01’,’t03’,’t05’);
Tno Tname Salary
T01 Rakesh 25600
T03 Sharmila 21000
T05 Shiv Om 13000
SUM FUNCTION
It is used to add the value of column.
Select sum(salary)from teacher where dept_no =’D05’;
Result is 44500
It adds the salary of Rakesh and Sangeeta.
MIN FUNCTION
It is used to find the minimum value of the column.
Select MIN(salary)from teacher;
Result is 13000.
MAX FUNCTION
It is used to find the maximum value of the column.
Select MAX (salary)from teacher;
Result is 25600.
AVG FUNCTION
It is used to find the average of the column.
Select AVG(salary) from teacher;
GROUP BY CLAUSE
This clause groups the rows in the result table by column that
have same values.
Select dept_no, MAX(salary)fromteacher group by dept_no;
HAVING CLAUSE
This clause is used to filter the grouped data.
Select dept_no ,MAX(salary)from teacher group by dept_no
having salary>21000;
Result is
CHARACTER /STRINGFUNCTIONS
CHAR ( )
SELECT CHAR (77, 121, 83, 81, 81, ’76’);
Result is:
‘MYSQL’
DEPT_NO MAX(salary)
D01 21000
D02 22000
D03 24000
D05 25600
DEPT_NO MAX(salary)
D02 22000
D03 24000
D05 25600
In this alphabetA is given code as 65 B 66 Upto Z 126
So in this way 77-M 121-Y 83-S 81-Q 76-L
And also 76 is in single quotesas it shows that it is the last one to
come.
CONCAT ( )
It is used to join two strings to form one string.
Select concat (‘sonia’, ’pahuja’);
Result is Soniapahuja
INSTR ( )
It is used to find the position of first occurrence of substring .
Select instr (‘sonia’,’o’);
Result is 2
It is displaying the position of O in the string Sonia.
LOWER ( )
It would convert the uppercase letters into lower case letters.
Select lower(‘MY SQL’);
Result is mysql
UPPER ( )
It would convert lower case letters into uppercase letters.
Select upper (‘mysql’);
Result is MYSQL
LENGTH ( )
It returns the length of specified expression and measured in
bytes.
Select length (‘mysql language’);
Result is 14
It also includesspacing as mysql language is of 13 characters and
1 is of space.
Select tname,length(tname)from teacher where
salary<20000;
Result is
TNAME LENGTH(TNAME)
Sangeeta 8
Vivek 5
TRIM( )
It trims or removes the unwantedspaces.
Select trim(‘ MYSQL LANGUAGE ‘);
Result is MYSQL LANGUAGE
Select concat(trim(tname),taddress)fromteacher where
doj<’2001-01-01’;
Result is
Concat(trim(tname),taddress)
Jugal mittal34,ramesh nagar
SUBSTR( )
Returns a specified no. of characters from the given character
expression.
In this we had to enterthe string with that starting index and
count that till how much is should continue.
Select SUBSTR(‘MYSQLLANGUAGE’,7,8);
Result is LANGUAGE
In this 7 is the position from where you have to start and total 8
characters you have to take.
Select SUBSTR(tname,2,4),salaryfrom teacher where
dept_no=’D05’;
Result is
SUBSTR(tname,2,4) SALARY
Akes 25600
Ange 18900
In this Rakesh and Sangeeta where chosen as they have dept _no
D05 and when we use SUBSTR then starting from position 2 and
total 4 characters gives this result.
MATHEMATICAL FUNCTIONS
POWER( )
Select POW(2,4);
Result is 16.
ROUND( )
This function roundsof a number.
Select ROUND(-1.23);
Result is -1
Select ROUND(1.58);
Result is 2
DATE FUNCTIONS
The default date in SQL is ‘YYYY-MM-DD’.
SYSDATE( )
It returns the current date along with the time.
Select SYSDATE();
Result is 2015-18-02 10:02:06
CURDATE( )
It returns the current date only.
Select CURDATE();
Result is 2015-18-02
CURTIME( )
It returns the current time.
Select CURTIME();
RESULT IS 10:05:07
DATE( )
It extracts the date part from the expression.
Select DATE(‘2009-05-20 01:02:03’);
Result is 2009-05-20
MONTH( )
It retrieves only the month part from the entire date.
Select MONTH(‘2009-05-09’);
Result is 5
MONTHNAME( )
Returns the full month name from the date.
Select MONTHNAME(‘2015-01-01’);
Result is JANUARY
YEAR( )
It returns the year from the date.
Select YEAR(‘2015-01-01’);
Result is 2015
DAYNAME( )
It returns the name of the week day for the date.
Select DAYNAME(‘2015-01-01’);
Result is THURSDAY
DAYOFYEAR( )
It returns the day of year for date, in the range 1 to 366.
Select DAYOFYEAR(‘2009-05-`20’);
Result is 140
JOINING TABLES
To join n tables together you need a minimum of (n-1) join
conditions.
Therefore to join five tables, a minimum of 3 joins are required.
Eg. 1st
teacher table we have and to join tables we have to create
2nd
table i.e. department table
CREATION OF TABLE
Create table department (dept_no char(5) primary key not
null, dept_name varchar(15));
In this way table is created.
DISPLAYINGSTRUCUTUREOF TABLE
DESCRIBEdepartment;
FIELD TYPE NULL KEY DEFAULT
DEPT_NO Char(5) No Pri Null
DEPT_NAME Varchar(15) Yes Null
INSERTINGVALUES IN TABLE
Insert into department values(‘D01’,’PHYSICS’);
Likewise insert all the values.
Now displaying table department i.e.
Select * from department;
Result is
DEPT_NO DEPT_NAME
D01 PHYSICS
D02 CHEMISTRY
D03 MATHS
D05 BIOLOGY
Now if we want to join teacherand department table then there
should be something common in them through which they can be
joined then in this case dept_nois common in both tables and in
both tables dept_no is set as primary key.
Select t.tname, d.dept_name from teacher t ,department d
where t.dept_no=d.dept_no;
Result is
TNAME DEPT_NAME
RAKESH BIOLOGY
JUGAL MITTAL CHEMISTRY
SHARMILA PHYSICS
SANGEETA BIOLOGY
SHIV OM CHEMISTRY
RAMESH MATHS
VIVEK PHYSICS
Mainly there are two types of join i.e.
EQUI – JOIN
The join in which joining condition is based on equality between
the values in the common column , is called as equi - join.It is
also called inner join or simple join.It is probablythe most
common type of join .We can use any type of relationaloperator
in equi join.
The above given example is of equi join i.e. the relation between
teacher and department tableaccording to dept_nois of equi join.
Join
Equi-join
Non- equi
join
NON EQUI – JOIN
When there is no common column in two tables and then we
perform a join. This type of join is called non equi-join.
Now, take an example
Let us create one more tablei.e. GRADE table.
Create table GRADE (grade char (1) primary key not null, minsal
double(8,2),maxsal double(8,2));
Now insertingvalues in the table.
Insert into GRADE values(‘A’,15000.00,21000.00);
Likewise insert all the values.
Displayingthe table
Select * from GRADE;
Grade Minsal Maxsal
A 15000.00 21000.00
B 15000.00 20999.00
C 10000.00 14999.00
D 5000.00 9000.00
If consider teacher and GRADE , there exists no common
column. So, it is not possible to perform the equi join.
There is no direct relationship between the two tables. The only
relationship between the above two tablesare that the salary in
the teacher tablein between the minsal and maxsal column of the
GRADE table. So, we cannot obtain the result using the =
operator. Thus the query will be:-
Select t.tname, t.salary, g.grade from teacher t, GRADE g
where t.salarybetween g.minsal and g.maxsal;
Tname Salary Grade
Rakesh 25600 A
Juggal 22000 A
Sharmila 21000 A
Sangeeta 19800 A
John roy 13500 C
Ramesh 24000 A
Vivek 12000 C
DATABASE MANAGEMENT SYSTEM

More Related Content

What's hot

Database User and Administrator
Database User and AdministratorDatabase User and Administrator
Database User and AdministratorA. S. M. Shafi
 
Architecture of dbms(lecture 3)
Architecture of dbms(lecture 3)Architecture of dbms(lecture 3)
Architecture of dbms(lecture 3)Ravinder Kamboj
 
Database Administration
Database AdministrationDatabase Administration
Database AdministrationBilal Arshad
 
data modeling and models
data modeling and modelsdata modeling and models
data modeling and modelssabah N
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overviewhonglee71
 
database language ppt.pptx
database language ppt.pptxdatabase language ppt.pptx
database language ppt.pptxAnusha sivakumar
 
Dbms classification according to data models
Dbms classification according to data modelsDbms classification according to data models
Dbms classification according to data modelsABDUL KHALIQ
 
SQL - שפת הגדרת הנתונים
SQL - שפת הגדרת הנתוניםSQL - שפת הגדרת הנתונים
SQL - שפת הגדרת הנתוניםמורן אלקובי
 
Data base management system
Data base management systemData base management system
Data base management systemashirafzal1
 
Naming convention in_database
Naming convention in_databaseNaming convention in_database
Naming convention in_databaseDavis Chen
 
Basic Concept of Database
Basic Concept of DatabaseBasic Concept of Database
Basic Concept of DatabaseMarlon Jamera
 
Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Salman Memon
 
Components and Advantages of DBMS
Components and Advantages of DBMSComponents and Advantages of DBMS
Components and Advantages of DBMSShubham Joon
 

What's hot (20)

Data models
Data modelsData models
Data models
 
Database User and Administrator
Database User and AdministratorDatabase User and Administrator
Database User and Administrator
 
Architecture of dbms(lecture 3)
Architecture of dbms(lecture 3)Architecture of dbms(lecture 3)
Architecture of dbms(lecture 3)
 
Database Administration
Database AdministrationDatabase Administration
Database Administration
 
data modeling and models
data modeling and modelsdata modeling and models
data modeling and models
 
Oracle Database Overview
Oracle Database OverviewOracle Database Overview
Oracle Database Overview
 
database language ppt.pptx
database language ppt.pptxdatabase language ppt.pptx
database language ppt.pptx
 
Dbms classification according to data models
Dbms classification according to data modelsDbms classification according to data models
Dbms classification according to data models
 
Chap14
Chap14Chap14
Chap14
 
SQL - שפת הגדרת הנתונים
SQL - שפת הגדרת הנתוניםSQL - שפת הגדרת הנתונים
SQL - שפת הגדרת הנתונים
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Database management system
Database management system Database management system
Database management system
 
Relational model
Relational modelRelational model
Relational model
 
Data base management system
Data base management systemData base management system
Data base management system
 
DbMs
DbMsDbMs
DbMs
 
Naming convention in_database
Naming convention in_databaseNaming convention in_database
Naming convention in_database
 
Basic Concept of Database
Basic Concept of DatabaseBasic Concept of Database
Basic Concept of Database
 
Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base Creating and Managing Tables -Oracle Data base
Creating and Managing Tables -Oracle Data base
 
Components and Advantages of DBMS
Components and Advantages of DBMSComponents and Advantages of DBMS
Components and Advantages of DBMS
 
11 Database Concepts
11 Database Concepts11 Database Concepts
11 Database Concepts
 

Viewers also liked

Cell therapies in heart failure
Cell therapies in heart failureCell therapies in heart failure
Cell therapies in heart failuredrucsamal
 
Presentatie Prof. dr. Doevendans en Prof. dr. Clevers
Presentatie Prof. dr. Doevendans en Prof. dr. CleversPresentatie Prof. dr. Doevendans en Prof. dr. Clevers
Presentatie Prof. dr. Doevendans en Prof. dr. CleversCVON
 
Cardiac tissue engineering
Cardiac tissue engineeringCardiac tissue engineering
Cardiac tissue engineeringMaryam Idris
 
Stem cells in cardiac repair
Stem cells in cardiac repairStem cells in cardiac repair
Stem cells in cardiac repairfelix677
 
Second Messenger: cAMP Pathway
Second Messenger: cAMP PathwaySecond Messenger: cAMP Pathway
Second Messenger: cAMP PathwayHotaru Imai
 
Stem cell & therapeutic cloning Lecture
Stem cell & therapeutic cloning LectureStem cell & therapeutic cloning Lecture
Stem cell & therapeutic cloning Lecturetest
 
Cells and organs of the immune system
Cells and organs of the immune systemCells and organs of the immune system
Cells and organs of the immune systemRashmimali
 
Induced Pluripotent Stem Cells and Somatic Cardiac Regeneration— An Explorato...
Induced Pluripotent Stem Cells and Somatic Cardiac Regeneration— An Explorato...Induced Pluripotent Stem Cells and Somatic Cardiac Regeneration— An Explorato...
Induced Pluripotent Stem Cells and Somatic Cardiac Regeneration— An Explorato...Robert Chen
 
Cardiovascular Tissue Engineering
Cardiovascular Tissue EngineeringCardiovascular Tissue Engineering
Cardiovascular Tissue EngineeringRaul Soto
 
Fluorescence spectroscopy
Fluorescence spectroscopyFluorescence spectroscopy
Fluorescence spectroscopyNimisha Dutta
 

Viewers also liked (13)

Cell therapies in heart failure
Cell therapies in heart failureCell therapies in heart failure
Cell therapies in heart failure
 
Presentatie Prof. dr. Doevendans en Prof. dr. Clevers
Presentatie Prof. dr. Doevendans en Prof. dr. CleversPresentatie Prof. dr. Doevendans en Prof. dr. Clevers
Presentatie Prof. dr. Doevendans en Prof. dr. Clevers
 
Critical Limb Ischemia (CLI)
Critical Limb Ischemia (CLI)Critical Limb Ischemia (CLI)
Critical Limb Ischemia (CLI)
 
Cardiac tissue engineering
Cardiac tissue engineeringCardiac tissue engineering
Cardiac tissue engineering
 
Stem cells in cardiac repair
Stem cells in cardiac repairStem cells in cardiac repair
Stem cells in cardiac repair
 
Second Messenger: cAMP Pathway
Second Messenger: cAMP PathwaySecond Messenger: cAMP Pathway
Second Messenger: cAMP Pathway
 
Stem cell & therapeutic cloning Lecture
Stem cell & therapeutic cloning LectureStem cell & therapeutic cloning Lecture
Stem cell & therapeutic cloning Lecture
 
Cells and organs of the immune system
Cells and organs of the immune systemCells and organs of the immune system
Cells and organs of the immune system
 
Cells of immune system
Cells of immune systemCells of immune system
Cells of immune system
 
Stem cell
 Stem cell Stem cell
Stem cell
 
Induced Pluripotent Stem Cells and Somatic Cardiac Regeneration— An Explorato...
Induced Pluripotent Stem Cells and Somatic Cardiac Regeneration— An Explorato...Induced Pluripotent Stem Cells and Somatic Cardiac Regeneration— An Explorato...
Induced Pluripotent Stem Cells and Somatic Cardiac Regeneration— An Explorato...
 
Cardiovascular Tissue Engineering
Cardiovascular Tissue EngineeringCardiovascular Tissue Engineering
Cardiovascular Tissue Engineering
 
Fluorescence spectroscopy
Fluorescence spectroscopyFluorescence spectroscopy
Fluorescence spectroscopy
 

Similar to DATABASE MANAGEMENT SYSTEM

Similar to DATABASE MANAGEMENT SYSTEM (20)

Database Management Lab -SQL Queries
Database Management Lab -SQL Queries Database Management Lab -SQL Queries
Database Management Lab -SQL Queries
 
Dbms Basics
Dbms BasicsDbms Basics
Dbms Basics
 
Dbms and sqlpptx
Dbms and sqlpptxDbms and sqlpptx
Dbms and sqlpptx
 
Unit 3 rdbms study_materials-converted
Unit 3  rdbms study_materials-convertedUnit 3  rdbms study_materials-converted
Unit 3 rdbms study_materials-converted
 
Oracle Introduction
Oracle Introduction Oracle Introduction
Oracle Introduction
 
Dbmsunit v
Dbmsunit vDbmsunit v
Dbmsunit v
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdf
 
Bank mangement system
Bank mangement systemBank mangement system
Bank mangement system
 
Database fundamentals
Database fundamentalsDatabase fundamentals
Database fundamentals
 
PT- Oracle session01
PT- Oracle session01 PT- Oracle session01
PT- Oracle session01
 
SQL for interview
SQL for interviewSQL for interview
SQL for interview
 
System i - DDL vs DDS Presentation
System i - DDL vs DDS PresentationSystem i - DDL vs DDS Presentation
System i - DDL vs DDS Presentation
 
csedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfcsedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdf
 
Database Management System ppt
Database Management System pptDatabase Management System ppt
Database Management System ppt
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
Chapter02
Chapter02Chapter02
Chapter02
 
Database Systems Concepts, 5th Ed
Database Systems Concepts, 5th EdDatabase Systems Concepts, 5th Ed
Database Systems Concepts, 5th Ed
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)
 
Week 1
Week 1Week 1
Week 1
 
Database-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptxDatabase-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptx
 

More from Sonia Pahuja

numerical method solutions
numerical method solutionsnumerical method solutions
numerical method solutionsSonia Pahuja
 
Bisection method solved questions
Bisection method solved questionsBisection method solved questions
Bisection method solved questionsSonia Pahuja
 
raster and random scan
raster and random scanraster and random scan
raster and random scanSonia Pahuja
 
Graphics exercise (b.tech)
Graphics exercise (b.tech)Graphics exercise (b.tech)
Graphics exercise (b.tech)Sonia Pahuja
 
Graphics exercise (b.tech)
Graphics exercise (b.tech)Graphics exercise (b.tech)
Graphics exercise (b.tech)Sonia Pahuja
 
Surajkund Mella Faridabad
Surajkund Mella FaridabadSurajkund Mella Faridabad
Surajkund Mella FaridabadSonia Pahuja
 
Determinant Matlab Code
Determinant Matlab CodeDeterminant Matlab Code
Determinant Matlab CodeSonia Pahuja
 
CODE Data Structures
CODE Data StructuresCODE Data Structures
CODE Data StructuresSonia Pahuja
 
Introduction to sets
Introduction to setsIntroduction to sets
Introduction to setsSonia Pahuja
 

More from Sonia Pahuja (14)

numerical method solutions
numerical method solutionsnumerical method solutions
numerical method solutions
 
Bisection method solved questions
Bisection method solved questionsBisection method solved questions
Bisection method solved questions
 
raster and random scan
raster and random scanraster and random scan
raster and random scan
 
Scanfill polygon
Scanfill polygonScanfill polygon
Scanfill polygon
 
Graphics exercise (b.tech)
Graphics exercise (b.tech)Graphics exercise (b.tech)
Graphics exercise (b.tech)
 
graphics notes
graphics notesgraphics notes
graphics notes
 
Graphics exercise (b.tech)
Graphics exercise (b.tech)Graphics exercise (b.tech)
Graphics exercise (b.tech)
 
Surajkund Mella Faridabad
Surajkund Mella FaridabadSurajkund Mella Faridabad
Surajkund Mella Faridabad
 
Business Ethics
Business Ethics Business Ethics
Business Ethics
 
Determinant Matlab Code
Determinant Matlab CodeDeterminant Matlab Code
Determinant Matlab Code
 
Gaussel Method
Gaussel MethodGaussel Method
Gaussel Method
 
CODE Data Structures
CODE Data StructuresCODE Data Structures
CODE Data Structures
 
Introduction to sets
Introduction to setsIntroduction to sets
Introduction to sets
 
Data Link Control
Data Link ControlData Link Control
Data Link Control
 

Recently uploaded

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Recently uploaded (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

DATABASE MANAGEMENT SYSTEM

  • 1. INTRODUCTION DBMS(Database Management System) is a collectionof inter- related programs that enable users to create, maintain database
  • 2. and control all the accesses to the database .Database is needed to develop the software so that multiple users can access the data. The basic processes that are supported by DBMS are:-  Storing the data.  Manipulation of database.  Querying the databaseto retrieve desired data.  Updating the content of database. Early InformationSystem When DBMS was not there in early times so peopleused early information system. Early information system used operating system to perform several operations. Problems DisorganizedDevelopment Application Programs File System Disk
  • 3. When peopleused to make their own programs then nobody knew what others have donedue to that data used to become redundant as peoplecould not access otherprograms. Data Isolation There was inconsistency in the programs. As multiple users used to design their own programs sitting at multiple places around the world. Modern Problems There was concurrencyin the system as many peopleused to updatesame information at same moment of time. Integrity Constraints There were no constraintsin such system. How Databaseis organized? Data itself need to be stored in a standard way so that database can retrieve and can manipulateit. There are no. of levels at which we can look at the storage of data.
  • 4. Some keywords involved in this process are:- Fig: DATABASE HIERARCHY Role of DBMS DATABASE FILE TABLE FIELD DATA TYPE VALUE
  • 6. This is your main file that encompasses the entire database. For example, school, bank, etc and that is saved to your hard drive or floppy disk or pen drive. TABLE:- A tableis a collection of data related to a single topic and a database is a collection of tables. For example a school database may comprise a no. of tables such as teacher personal details, teacher salary data, student details, student mark sheet etc. Note that each table is related to a single topic while a database is related to multiple tables. RECORDS:- Record is the information related to one entity. A tableis made up of a no. of rows or records. In our example each record or row of teacher personal details tablewould contain data of a specific teacher or a student details table would contain data on a specific student. FIELDS:- Field is the individual sub componentof one record. Each database tableis partitioned into one or more fields. Fields are different categories within a table. Example roll_no, name, dob, address, etc. The FIELD NAME is a program variable associated with this field. This name should be meaningful and a single token (no blanks).
  • 7. DATA TYPES:- Data types are the propertiesof each field. For example roll_no as number, name as text, dob as date etc. A tablecan have up to 254 columns which may have different or same data types and sets of values (domains), respectively. Possible domains are alphanumeric data (strings), numbers and date formats. Oracle offers the following basic data types: _ char(n): Fixed-length characterdata (string), n characters long. The maximum size for n is 255 bytes (2000 in Oracle8). Note that a string of type char is always padded on right with blanks to full length of n. Example: char(40) _ varchar2(n):Variable-length characterstring. The maximum size for n is 2000 (4000 in Oracle8). Only the bytes used for a string require storage. Example: varchar2(80) _ number(o; d): Numeric data type for integers and reals. o = overall number of digits, d = number of digits to the right of the decimal point. Maximum values: o =38, d= �84 to +127. Examples: number(8), number(5,2) Note that, e.g., number(5,2)cannot contain anything larger than 999.99without resulting in an error. Data types derived from number are int[eger], dec[imal], smallint and real. _ date: Date data type for storing date and time.
  • 8. The default format for a date is: DD-MMM-YY. Examples: '13- OCT-94', '07-JAN-98' _ long: Characterdata up to a length of 2GB. Only one long column is allowed per table. Let us take an example of student table with followingdata in a relational databasefor a school:- Roll_no Name Dob Address Number Character Date Character 1001 Ridhi Narang 1996-04-07 56/18 Kamla nagar 1002 Ananay Narang 2001-02-02 56/19 kamla nagar 1003 Aditi Narang 1998-08-11 56/19 kamla nagar 1004 Pushkar Narang 1994-06-17 56/18 kamla nagar The student tablehas four columns and four rows. The data types for a column indicate the type of data that may be stored in that column.  Field name:- Roll_no, Name, Dob, Address.  Data type:- Number, Character, Date.
  • 9. Structured query language(SQL) SQL is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS), or for stream processing in a relational data stream management system (RDSMS). Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language and a data manipulation language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. Although SQL is often described as, and to a great extent is, a declarative language (4GL), it also includes procedural elements. SQL was one of the first commercial languages for Edgar F. Codd's relational model, as described in his influential 1970 paper, "A Relational Model of Data for Large Shared Data Banks."Despite not entirely adhering to the relational model as described by Codd, it became the most widely used database language. SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International Organization for Standardization (ISO) in 1987. Since then, the standard has been revised to include a larger set of features. Despite the existence of such standards, though, most SQL code is not completely portable among different database systems without adjustments. History
  • 10. SQL was initially developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This version, initially called SEQUEL (Structured English Query Language), was designed to manipulate and retrieve data stored in IBM's original quasi-relational database management system, System R, which a group at IBM San Jose Research Laboratory had developed during the 1970s. The acronym SEQUEL was later changed to SQL because "SEQUEL" was a trademark of the UK-based Hawker Siddeley aircraft company. In the late 1970s, Relational Software, Inc. (now Oracle Corporation) saw the potential of the concepts described by Codd, Chamberlin, and Boyce, and developed their own SQL-based RDBMS with aspirations of selling it to the U.S. Navy, Central Intelligence Agency, and other U.S. government agencies. In June 1979, Relational Software, Inc. introduced the first commercially available implementation of SQL, Oracle V2 (Version2) for VAX computers. After testing SQL at customer test sites to determine the usefulness and practicality of the system, IBM began developing commercial products based on their System R prototype including System/38, SQL/DS, and DB2, which were commercially available in 1979, 1981, and 1983, respectively. Classificationof SQL statements
  • 11. 1.Data definitionlanguage (DDL):-Thesestatements are used to create and modify the structureof your tables. When you execute a DDL statement, it takes effect immediately. Eg. CREATE TABLE, ALTER TABLE, DROP TABLE etc. 2.Data manipulation language (DML):-These statements are used to manipulatethe data base objects. By data manipulation we mean:-  The RETRIEVAL of information stored in database.  The INSERTION of new information into database.  The DELETION of information from the database.  The MODIFICATION of data stored in database. Eg. SELECT, INSERT, DELETE, UPDATE etc. The DMLs are basically of two types:-
  • 12. ProceduralDMLs require a user to specify what data is needed and how to get it. Non procedural require a user to specify what data is needed without specifying how to get it. 3. Utilitystatement:-DESCRIBE, EXPLAIN, HELP etc. 4. Database control language (DCL):- These statements are used for database administration. Eg. GRANT, DENY, REVOKE etc. 5. Locking and transactional statements:- Eg. LOCK TABLES, UNLOCK TABLES, COMMIT, ROLL BACK etc. DMLs Procedural Non- Procedural
  • 13. CASE SENSTIVITY IN SQL STATEMENTS A case sensitivity rule in SQL statements vary for different part of statements and also dependson what you are referring to and the OS of the machine the server is running:-  SQL Keywords and FunctionNames Keywords and function names are not case sensitive.They can be given in any lettercase. Eg. Select now( ); Select NOW( ); Select Now( ); Theses all statement will execute and producethe same results.  Column and index names Column and index names are not case sensitive in SQL. Eg. Select name from teacher; Select NAME from teacher; Select Name from teacher;
  • 14.  Alias names Aliases are case sensitive. We can specify an alias in any lettercase, but we must refer to it elsewhere in the query using the same case. Comments in SQL Comments can be useful for documentingQueries that you store in files. There are two recommended comment styles.  First, anything from a ’#’ character to the end of a line is considered a comment. Eg. #This is a single line comment  Second, C-style comments are allowed as well. That is anything between the ‘/*’ and ‘/*’ beginning and ending markers is considered a comment. Eg. /* This is also a single line comment */ /* This , however ,
  • 15. is a multipleline comment*/ DATA TYPES OF SQL A datatypein a programming language is a set of data with values having predefined characteristics. 1.INTEGER TYPE SIZE INT 4 bytes SMALLINT 2 bytes MEDIUMINT 3 bytes BIGINT 8 bytes TINYINT 1 byte 2.FLOAT It is a small number with a floating decimal point. It’s size is 4 bytes. 3.TEXT/STRINGTYPES TYPE SIZE DESCRIPTION CHAR Length bytes A fixed length field
  • 16. from 0 to 255 characters long. VARCHAR String length + 1 bytes A fixed length field from 0 to 255 characters long. TINYTEXT String length + 1 bytes A string with max length of 255 characters. TEXT String length + 2 bytes A string with max length of 65535 characters. MEDIUMTEXT String length + 3 bytes A string with max length of 16777215 characters. LONGTEXT String length + 4 bytes A string with max length of 4294967295 characters. 4.DATE TYPES TYPE SIZE DESCRIPTION DATE 3 bytes In the format of YYYY- MM-DD DATETIME 8 bytes In the format of YYYY- MM-DD HH:MM:SS TIMESTAMP 4 bytes In the format of YYYYMMDDHHMMSS ; acceptablerange ends in the year 2037
  • 17. TIME 3 bytes In the format of HH:MM:SS HOW TO CHOOSE YOUR DATA TYPE  Identify whether a column should be a text, number, or data type.  Choose the most appropriatesubtypefor each column.  Set the maximum length for text and number columns as well as attributes. OPERATORS IN SQL Operators are componentsof expressions to specify the interactionsand conditionsthat affect and limit the range of values in a result set. OPERATOR PRECEDENCE Highest precedence := 1 OR, XOR, || 2 &&, AND 3 BETWEEN, CASE,WHEN, THEN, ELSE 4 =,<=, >=, <, >, IS, LIKE, IN 5 |
  • 18. 6 & 7 <<, >> 8 -,+ 9 *,%, / 10 ^ 11 -(UNARY MINUS), ~(UNARY BIT INVERSION) 12 !, NOT Lowest BINARY COLATE ARITHMETIC OPERATORS:-These operatorsare used to perform mathematical calculations. OPERATOR DESCRIPTION + Addition - Subtraction * Multiplication / Division % Modulus COMPARISON OPERATORS:-These are also called as relation operators. These are used for comparison purposes. OPERATORS DESCRIPTION = Equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to != Not equal to
  • 19. BOOLEAN/LOGICAL OPERATORS:- These operatorsare either true or false. OPERATORS DESCRIPTION AND Return T if both inputs are T OR Return T if any one of the input is T NOT Change the input from T to F or from F to T SQL WORD OPERATORS:- OPERATOR DESCRIPTION BETWEEN Returns values in given range i.e. in b/w the inputs IN Returns values in specified subset LIKE Return values that matches a simple pattern NOT Negates an operation means opposite CONSTRAINTS
  • 20.  Not null:-It ensures that we cannot leave a column as null Eg. Name is always mandatory.  Default:-It prevents null from occurring if a row is inserted without a value for the column.  Check:-It defines a condition that each row must satisfy. KEYS KEYS PRIMARY ALTERNA TE CANDIDATE FOREIGN
  • 21.  Primary key:-It helps us to uniquelyidentifies each row in table. It can neitherbe normal attributei.e. guaranteed to be unique(suchas SSN in a tablewith no more than one record per person) or it can be generated by DBMS(such as a globally uniqueidentifier). Based on the primary key the database system ensures that no duplicationappearin the table. To choose a primary key for an entity must have following properties:-  The values must not change or become null during the life of each entity. This table shows some of the primary key fields which uniquelyidentify the tableto make relation with another table. TABLE NAME PRIMARY KEY ATTRIBUTE STUDENT ROLL_NO CUSTOMER CUST_ID TEACHER TNO DEPARTMENT DEPT_NO EMP EMP_NO DEPT DEPT_NO
  • 22.  Foreign key:-It is declared as primary key in othertable and used to enforce referential integrity. It identifies a column or set a column in one table that refers to a column or set of columns in anothertable. The columns in the referencing tablemust be the primary key or other candidatekey in the referenced table. A table may have multiple foreign keys. Primary keys and foreign keys in table Primary key Foreignkey TEACHER TNO TADDRESS SALARY DEPT_NO DOJ DEPARTMENT DEPT_NO DEPT_NAME
  • 23.  Candidatekey:-It is one that can identify each row of a table uniquely. Generally, a candidatekey becomes the primary key of the table. There are three fundamental demands on the candidatekeys that we should never deviate from:-  It must be unique.  It cannot hold NULLs.  It should never change i.e. should hold the same value during its lifetime. E.g. SSN, E_ID, D_NO, etc.  Alternate keys:-If tablehas more than one candidatekey, then one is called primary key and rest are called Alternative keys. Let us take an example of our class. Supposein our class we have to select our class monitor. So A, B, C and D stand for that post. So A, B, C and D are candidatefor monitor so these are candidatekeys. We select B as a monitor so B is a primary key and A, C and can be monitor but not selected as a monitor so they are alternative choice and are called alternative keys. TABLE/COLUMNNAMING CONVENTIONS The table-name/field/column can be assigned according to the following rules:-  A name will start with either a letter or from an underscore.
  • 24.  After the first characterwe can use any combination of letters, digits, or underscore.  A name will not start with two underscores.  A name will not include one or more empty spaces. i.e. a name will be made in one word.  If the name is combination of words, each word part will start in uppercase. E.g. DateHired, DriversLicenseNumber etc. SOME SQL COMMANDS CREATE:-This command is used to create the tables. The creation commands requires:-  Name of the table  Name of fields  Definations for each field. The syntax for creating a table is: Create table<table_name >( Field1 data type, field2 type, etc……….); Example
  • 25. Create table teacher (tno varchar (4) primary key not null, tname char(25), taddress varchar(30),salaryfloat, dept_no char(4), doj date); In this way teacher tableis created. DESCRIBE:-This command is used to describe the structureof our table It is used to show the attributesof the tablewith the constraint NULL/NOT NULL. DESCRIBEteacher; Output is FIELD TYPE NULL KEY DEFAULT Tno Varchar(4) No Pri Tname Varchar(25) Yes Null Taddress Varchar(25) Yes Null Salary Float Yes Null Dept_no Char(4) Yes Null Doj Date Yes Null INSERTINGDATA:- Insert command is used to insert new rows in a table. It is a DML command. Data manipulationcapabilities allow one to retrieve and modify the contentsof the table. The syntax for insert statement is:-
  • 26. Insert into<table_name> values( value1, value2,etc……..); Insert into teacher values (‘t01’,’rakeshsharma’,’245 malviya nagar’, 25600,’d05’,’2012-12-12’); This is how we insert values. SELECT:-It is used to retrieve the information from the tables.  The select list must include atleast one column name or one expression. If more than one column or expression element is included, they must be separated by a comma.  We can assign an alias to a column name or expression.  Although the select clause is the only required element in a select statement you cannot retrieve data from a table unless you also specify a FROM clause. FROM CLAUSE:-It specifies the tables that are used to retrieve values. This clause is followed by a space and then the name of database being used as a source of information. Retrievingall the columns:- If you want to see every column of table the astrerisk(*) is a convenient short hand that means all column.
  • 27. WHERECLAUSE:-It specifies the condition either it would be true or false. It specifies the search condition used to determine the data that will appear in the result table. The syntax is Select column name1, column name2……..fromtable name [where condition]; The square bracket in where clause means that the clause is optionali.e. you can use select statement without using this clause. The where clause expects three elements:-  Column name  Comparison operator  Column name, constantsor list of values The where clause goes through the entire table one row at a time and examines each row to determine if the condition is true or false. As you can see a where clause must contain atleast one expression that defines which rows the select statement returns. When you specify more than one condition in where clause, those condition are connected by an AND or an OR operator.The operatorsspecify which conditionor combination of conditions must be met. Select *from teacher; This would display all the result i.e. the complete teachertable.
  • 28. TNO TNAME TADDRESS SALARY DEPT_NO DOJ T01 RAKESH 245 MALVIYA NAGAR 25600 D05 2001- 12-12 T02 JUGAL MITTAL 34,RAMESH NAGAR 22000 D02 1999- 07-03 T03 SHARMILA D-31 ASHOK VIHAR 21000 D01 2000- 06-06 T04 SANGEETA G-35 MALVIYA NAGAR 18900 D05 2000- 02-20 T05 SHIV OM R-44 KIRTI NAGAR 13000 D02 2001- 09-22 T06 RAMESH B-42 SHALIMAR BAGH 24000 D03 1997- 07-03 T07 VIVEK E-33 ROHINI WEST 12000 D01 2001- 10-12 RETRIEVING FROM SPECIFIC COLUMN 1. Select tno, tname, salaryfrom teacher; This would display tno, tname, salary from teacher table. 2. Select tno, tname, salaryfrom teacher where tno=T06; This would give details of T06 as his tno i.e. of ramesh. 3. Select tno, tname from teacher where tname like’R%’;
  • 29. This would give details of Rakesh and Ramesh. LIMIT CLAUSE:-It is used to limit the no. of rows. It takes 2 arguments i.e. from where to start and upto what extent it should proceed. Select * from teacher LIMIT 2,5; It would display result as all the details of T03 uptoT07. Tno Tname Taddress Salary Dept_no Doj T03 SHARMILA d-31 ashok vihar 21000 D01 2000- 06-06 T04 SANGEETA g-35 malviya nagar 18900 D05 2000- 02-20 T05 SHIV OM r-44 kirti nagar 13000 D02 2001- 09-22 T06 RAMESH b-42 shalimar bagh 24000 D03 1997- 07-03 T07 VIVEK e-33 rohini west 17000 D01 2001- 10-12
  • 30. UPDATINGTABLE This is used to modify existing data in the table. The basic syntax for UPDATE statement is:- UPDATE tableset field=value [, field=value][where conditions]; The UPDATE is followed by a tablename and sat clause with pair of column names and associated expressions that are being assigned to the column. Eg. Update teacher set tname=RAMU where tname=Ramesh; It would make changes in tableas ramesh would be modified to RAMU. Using expressionin UPDATE Scalar expression can be used in UPDATE command i.e. we can also set all the rows of particularcolumn wth a single value. Eg. UPDATEteacher set salary =salary+500 where salary<15000. Result is Tno Tname Taddress Salary Dept_no Doj
  • 31. T05 Shivam om r-44,kirti nagar 13500 D02 2001-09- 22 Updatingwith multiple columns We can updatemore than 1 column using UPDATE command. Eg. UPDATE teacherset tname=’john Roy ’ , dept_no=’D03’where tname =’shiv om’; Result would be It will replace shiv om to john roy. ALTER TABLE It allows you to make changes in the existing table in many ways such as :- 1.Adding column:- This would help us to add new column. Alter table teacher add column age int after salary; Result would be a new column named as AGE would be added after salary column. 2.Adding constraint:- This would help us to add constraint such as not null , primary key etc. Alter table teacher modify tname varchar(10)not null; It would make the changes in the existing table.
  • 32. ORDERINGTHE DATABASE It determines the order of rows in the result tablei.e. either in ASC or DESC. By default order is ASC. Select * from teacher order by salary; This would display all the details along with salary in ascending order DELETE STATEMENT It deletes the rows from table and returns the no. of rows deleted. DELETE from teacher; It would delete all the rows. DELETE from teacher where tno=’T01’; It would delete only a particularrow i.e. T01. DROP TABLE It would delete the whole table. DROP TABLE teacher; Result would be that now no teachertable exists.
  • 33. COUNTFUNCTION It is used to count the no. of values in a given column, or no. of rows in the table. Select count(*) from teacher; Result is 7 As it countsthe total no. of teachers in the teacher table. DISTINCT CLAUSE It is used to extract uniquethings from the table. The syntax of distinct clause is:- Select DISTINCT column name from tablename; Select count( distinctdept_no) from teacher; Result is 4 Select distinct count(dept_no)fropmteacher; This query doesn’t work accordingly as distinct dept_no would not be countedall the rows would be counted. LIKE CLAUSE
  • 34. The LIKE operatoris used to check if field values match a specified pattern, and searches for less-than-exact but similar values. LIKE can be applied to only CHAR and VARCHAR fields. The LIKE searches a characterfield to see if part of it matches a string. The LIKE clause is used to select rows which are matching wildcards patterns. Note that the patternsare case sensitivity i.e. the uppercase letters do not match lower case letters. The syntax is as: Select column name1, column name2,…… From table name Where column name like ’%’; QS:- Write a query to display teacherno and teachername whose name started with alphabet ‘R’. Select tno, tname from teacher where tname like ‘R%’; Tno Tname T01 Rakesh Sharma T06 Ramesh kumar ALL CLAUSE The ALL clause is same as that when you do not specify DISTINCT. The ALL clause retains the duplicaterows.
  • 35. The syntax is as: Select ALL column name from table name; Select ALL tname from teacher; BETWEEN CLAUSE The BETWEEN operatoris used to check if field values are within a specified inclusive range BETWEEN is sensitive to order, and the first value in the clause must be in alphabeticor numeric order. The syntax is as: Select column name1, column name2,….. from tablename where column name between value1 and value2; QS:- Write a query to display teacherno, teacher name and salary of all the teachers whose salary is between 15000AND 20000. Select tno, tname, salary from teacher where salary between 15000AND 20000; Tno Tname salary
  • 36. T04 Sangeeta 18900 IN CLAUSE The IN clause is used to specify condition based on a list. The IN operatorselects values that match any value present in the list of values. The syntax is: Select column name1, column name2,…. From table name where column name IN ( value1,value2,……,valuen); QS:- Write a query to display teacherno, teacher name and salary of the teachers t01,t02and t03. Select tno, tname, salary from teacher where tno IN(‘t01’,’t03’,’t05’); Tno Tname Salary T01 Rakesh 25600 T03 Sharmila 21000 T05 Shiv Om 13000 SUM FUNCTION
  • 37. It is used to add the value of column. Select sum(salary)from teacher where dept_no =’D05’; Result is 44500 It adds the salary of Rakesh and Sangeeta. MIN FUNCTION It is used to find the minimum value of the column. Select MIN(salary)from teacher; Result is 13000. MAX FUNCTION It is used to find the maximum value of the column. Select MAX (salary)from teacher; Result is 25600. AVG FUNCTION It is used to find the average of the column. Select AVG(salary) from teacher; GROUP BY CLAUSE This clause groups the rows in the result table by column that have same values.
  • 38. Select dept_no, MAX(salary)fromteacher group by dept_no; HAVING CLAUSE This clause is used to filter the grouped data. Select dept_no ,MAX(salary)from teacher group by dept_no having salary>21000; Result is CHARACTER /STRINGFUNCTIONS CHAR ( ) SELECT CHAR (77, 121, 83, 81, 81, ’76’); Result is: ‘MYSQL’ DEPT_NO MAX(salary) D01 21000 D02 22000 D03 24000 D05 25600 DEPT_NO MAX(salary) D02 22000 D03 24000 D05 25600
  • 39. In this alphabetA is given code as 65 B 66 Upto Z 126 So in this way 77-M 121-Y 83-S 81-Q 76-L And also 76 is in single quotesas it shows that it is the last one to come. CONCAT ( ) It is used to join two strings to form one string. Select concat (‘sonia’, ’pahuja’); Result is Soniapahuja INSTR ( ) It is used to find the position of first occurrence of substring . Select instr (‘sonia’,’o’); Result is 2 It is displaying the position of O in the string Sonia. LOWER ( ) It would convert the uppercase letters into lower case letters. Select lower(‘MY SQL’); Result is mysql UPPER ( )
  • 40. It would convert lower case letters into uppercase letters. Select upper (‘mysql’); Result is MYSQL LENGTH ( ) It returns the length of specified expression and measured in bytes. Select length (‘mysql language’); Result is 14 It also includesspacing as mysql language is of 13 characters and 1 is of space. Select tname,length(tname)from teacher where salary<20000; Result is TNAME LENGTH(TNAME) Sangeeta 8 Vivek 5 TRIM( ) It trims or removes the unwantedspaces. Select trim(‘ MYSQL LANGUAGE ‘); Result is MYSQL LANGUAGE
  • 41. Select concat(trim(tname),taddress)fromteacher where doj<’2001-01-01’; Result is Concat(trim(tname),taddress) Jugal mittal34,ramesh nagar SUBSTR( ) Returns a specified no. of characters from the given character expression. In this we had to enterthe string with that starting index and count that till how much is should continue. Select SUBSTR(‘MYSQLLANGUAGE’,7,8); Result is LANGUAGE In this 7 is the position from where you have to start and total 8 characters you have to take. Select SUBSTR(tname,2,4),salaryfrom teacher where dept_no=’D05’; Result is SUBSTR(tname,2,4) SALARY Akes 25600 Ange 18900
  • 42. In this Rakesh and Sangeeta where chosen as they have dept _no D05 and when we use SUBSTR then starting from position 2 and total 4 characters gives this result. MATHEMATICAL FUNCTIONS POWER( ) Select POW(2,4); Result is 16. ROUND( ) This function roundsof a number. Select ROUND(-1.23); Result is -1 Select ROUND(1.58); Result is 2
  • 43. DATE FUNCTIONS The default date in SQL is ‘YYYY-MM-DD’. SYSDATE( ) It returns the current date along with the time. Select SYSDATE(); Result is 2015-18-02 10:02:06 CURDATE( ) It returns the current date only. Select CURDATE(); Result is 2015-18-02 CURTIME( ) It returns the current time. Select CURTIME(); RESULT IS 10:05:07 DATE( ) It extracts the date part from the expression. Select DATE(‘2009-05-20 01:02:03’); Result is 2009-05-20
  • 44. MONTH( ) It retrieves only the month part from the entire date. Select MONTH(‘2009-05-09’); Result is 5 MONTHNAME( ) Returns the full month name from the date. Select MONTHNAME(‘2015-01-01’); Result is JANUARY YEAR( ) It returns the year from the date. Select YEAR(‘2015-01-01’); Result is 2015 DAYNAME( ) It returns the name of the week day for the date. Select DAYNAME(‘2015-01-01’); Result is THURSDAY
  • 45. DAYOFYEAR( ) It returns the day of year for date, in the range 1 to 366. Select DAYOFYEAR(‘2009-05-`20’); Result is 140 JOINING TABLES To join n tables together you need a minimum of (n-1) join conditions. Therefore to join five tables, a minimum of 3 joins are required. Eg. 1st teacher table we have and to join tables we have to create 2nd table i.e. department table CREATION OF TABLE Create table department (dept_no char(5) primary key not null, dept_name varchar(15)); In this way table is created. DISPLAYINGSTRUCUTUREOF TABLE DESCRIBEdepartment; FIELD TYPE NULL KEY DEFAULT DEPT_NO Char(5) No Pri Null DEPT_NAME Varchar(15) Yes Null
  • 46. INSERTINGVALUES IN TABLE Insert into department values(‘D01’,’PHYSICS’); Likewise insert all the values. Now displaying table department i.e. Select * from department; Result is DEPT_NO DEPT_NAME D01 PHYSICS D02 CHEMISTRY D03 MATHS D05 BIOLOGY Now if we want to join teacherand department table then there should be something common in them through which they can be joined then in this case dept_nois common in both tables and in both tables dept_no is set as primary key. Select t.tname, d.dept_name from teacher t ,department d where t.dept_no=d.dept_no; Result is TNAME DEPT_NAME RAKESH BIOLOGY JUGAL MITTAL CHEMISTRY SHARMILA PHYSICS SANGEETA BIOLOGY SHIV OM CHEMISTRY
  • 47. RAMESH MATHS VIVEK PHYSICS Mainly there are two types of join i.e. EQUI – JOIN The join in which joining condition is based on equality between the values in the common column , is called as equi - join.It is also called inner join or simple join.It is probablythe most common type of join .We can use any type of relationaloperator in equi join. The above given example is of equi join i.e. the relation between teacher and department tableaccording to dept_nois of equi join. Join Equi-join Non- equi join
  • 48. NON EQUI – JOIN When there is no common column in two tables and then we perform a join. This type of join is called non equi-join. Now, take an example Let us create one more tablei.e. GRADE table. Create table GRADE (grade char (1) primary key not null, minsal double(8,2),maxsal double(8,2)); Now insertingvalues in the table. Insert into GRADE values(‘A’,15000.00,21000.00); Likewise insert all the values. Displayingthe table Select * from GRADE; Grade Minsal Maxsal A 15000.00 21000.00 B 15000.00 20999.00 C 10000.00 14999.00 D 5000.00 9000.00 If consider teacher and GRADE , there exists no common column. So, it is not possible to perform the equi join.
  • 49. There is no direct relationship between the two tables. The only relationship between the above two tablesare that the salary in the teacher tablein between the minsal and maxsal column of the GRADE table. So, we cannot obtain the result using the = operator. Thus the query will be:- Select t.tname, t.salary, g.grade from teacher t, GRADE g where t.salarybetween g.minsal and g.maxsal; Tname Salary Grade Rakesh 25600 A Juggal 22000 A Sharmila 21000 A Sangeeta 19800 A John roy 13500 C Ramesh 24000 A Vivek 12000 C