SlideShare a Scribd company logo
Relational Database
Database :
• A collection of data is referred to as database and a
database(management)system is basically a computer based
record keeping system.
• It maintains any information that may be necessary to the
decision-making involved in the management of the organization.
• The intention of a database is that the same collection of data
should serve as many applications as possible.
• Database would permit not only the retrieval of data but also
continuous modification of data needed for control of operations.
• A traditional file processing system suffers from some major limitations like
- data redundancy,
- data inconsistency ,
- unsharable data ,
- unstandardized data ,
- insecure data…
• On the other hand , a database system overcomes all these limitations and ensure continues
efficiency..
• The advantages provided by a database system are :
- Reduced data redundancy
- Controlled data inconsistency
- Shared data
- Standardized data
- Secured data (Unauthorized access is not restricted)
Relational Database Model :
• Different types of DBMS are available and their classification is done
based on the underlying data model.
• The most commonly used data model is Relational Data Model.
• Other types of data models include
- object-oriented data model,
-Network data model,
- document model,
- hierarchical data model.
Relational Database Model :
• In relational model, tables are called relations.
Unit 10 - Realtional Databases.pptxxxxxxxxx
The commonly used terminologies in relational data model :
i) ATTRIBUTE: The columns of a relation are the attributes which are also
referred as fields. For example, GUID, GName, GPhone and GAddress are
attributes of relation GUARDIAN.
ii) TUPLE: Each row of data in a relation (table) is called a tuple.
iii) DOMAIN: It is collection of values from which the value is derived for a
column. Usually, a data type is used to specify domain for an attribute. For
example, in STUDENT relation, the attribute RollNumber takes integer
values and hence its domain is a set of integer values. Similarly, the set of
character strings constitutes the domain of the attribute SName.
iv) DEGREE: The number of attributes in a relation is called the Degree of
the relation.
v) CARDINALITY: The number of tuples in a relation is called the Cardinality
of the relation.
Unit 10 - Realtional Databases.pptxxxxxxxxx
Properties of a Relation :
▪ Atomicity : Each column assigned a unique name and must have
atomic(indivisible) value i.e. a value that can not be further subdivided.
▪ No duplicity: No two rows of relation will be identical i.e. in any two rows
value in at least one column must be different.
▪ All items in a column are homogeneous i.e.same data type.
▪ Ordering of rows and column is immaterial.
SQL
• SQL is an acronym of Structured Query Language
• It is a standard language developed and used for accessing and modifying
relational databases.
• The SQL language was originally developed at the IBM research laboratory
in San José.
• SQL is being used by many database management systems. Some of them
are:
• ➢MySQL
• ➢PostgreSQL
• ➢Oracle
• ➢SQLite
• ➢Microsoft SQL Server
Views
• A view is a kind of table whose contents are taken from other tables
depending upon a condition.
• View does not contain data of their own.
• A view is a (virtual) table that does not really exist in its own right but
instead derived from one or more underlying base tables .
Eg :
create view gooditems as select * from items where price>12;
Itemno Itemname Price
I1 Milk bread 15.00
I4 Ice cream 16.00
i7 Cake 20.00
Itemno Itemname Price
I1 Milk bread 15.00
I2 Cream Biscuit 12.00
I4 Ice cream 16.00
I5 Cold drink 10.00
I7 Cake 20.00
KEYS IN A DATABASE :
• Key plays an important role in relational database; it is used for
identifying unique rows from table & establishes relationship among
tables on need.
Types of keys in DBMS :
Primary Key – A primary is a column or set of columns in a table that
uniquely identifies tuples in that table. Primary keys must contain
UNIQUE values, and cannot contain NULL values.
Primary Key
Itemno Itemname Price
I1 Milk bread 15.00
I2 Cream Biscuit 12.00
I4 Ice cream 16.00
I5 Cold drink 10.00
I7 Cake 20.00
KEYS IN A DATABASE :
Composite Primary Key - Combination of more than one attribute
provides a unique value for each row .The primary key consists of more
than one attribute , it is called composite primary key .
KEYS IN A DATABASE :
• Candidate Key –It is an attribute or a set of attributes or keys participating
for Primary Key, to uniquely identify each record in that table.
• Alternate Key – Out of all candidate keys, only one gets selected as
primary key, remaining keys are known as alternate or secondary keys.
• Foreign Key –A non-key attribute , whose values are derived from the
primary key of some other table , is known as Foreign key in its current
table.
• Referential Integrity – It is system of rules that a DBMS uses to ensure that
relationships between records in related tables are valid , and that users
don’t accidentally delete or change related data.
Unit 10 - Realtional Databases.pptxxxxxxxxx
Key features of MYSQL are :
• Open Source & Free of Cost: It is Open Source and available at free of
cost.
• Portability: Small enough in size to instal and run it on any types of
Hardware and OS like Linux,MS Windows or Mac etc.
• Security : Its Databases are secured & protected with password.
• Connectivity : Various APIs are developed to connect it with many
programming languages.
• Query Language : It supports SQL (Structured Query Language) for
handling database.
• Data Types : It provides many data types to support different types of
data .
Classification Of SQL statements :
• DDL (Data Definition Language) - To create database and table
structure-commands like CREATE , ALTER , DROP etc.
• DML (Data Manipulation Language) - Record/rows related
operations.commands like SELECT...., INSERT..., DELETE..., UPDATE....
etc.
• DCL (Data Control Language) - used to manipulate permissions or
access rights to the tables. commands like GRANT , REVOKE etc.
• Transactional control Language - Used to control the
transactions.commands like COMMIT, ROLLBACK, SAVEPOINT etc
Difference between DDL and DML :
DDL DML
It stands for Data Definition Language. It stands for Data Manipulation Language.
It is used to create database schema and can be used to
define some constraints as well.
It is used to add, retrieve, or update the data.
It basically defines the column (Attributes) of the table.
It adds or updates the row of the table. These rows are
called tuples.
Basic commands present in DDL are CREATE, DROP,
RENAME, ALTER, etc.
BASIC commands present in DML are UPDATE, INSERT etc.
DDL does not use WHERE clause in its statement. While DML uses WHERE clause in its statement.
DDL is used to define the structure of a database. DML is used to manipulate the data within the database.
DDL statements are typically executed less frequently
than DML statement
DML statements are frequently executed to manipulate
and query data.
DDL statements are not used to manipulate data directly. DML statements are used to manipulate data directly.
Examples of DDL commands: CREATE TABLE,
ALTER TABLE, DROP TABLE, TRUNCATE TABLE,
and RENAME TABLE.
Examples of DML commands: SELECT, INSERT,
UPDATE, DELETE .
Data type in MySQL :
• Numeric Data Types:
INTEGER or INT – up to 11 digit number without decimal.
SMALLINT – up to 5 digit number without decimal.
FLOAT (M,D) or DECIMAL(M,D) or NUMERIC(M,D) Stores Real numbers upto
M digit length (including .) with D decimal places.
e.g. Float (10,2) can store 1234567.89
• Date & Time Data Types:
DATE - Stores date in YYYY-MM-DD format.
TIME - Stores time in HH:MM:SS format.
• String or Text Data Type:
CHAR(Size) A fixed length string up to 255 characters. (default is 1)
VARCHAR(Size):A variable length string up to 255 characters.
Difference between Char and Varchar :
S.no CHAR VARCHAR
1.
CHAR datatype is used to store character strings of
fixed length.
VARCHAR datatype is used to store character strings
of variable length.
2.
In CHAR, If the length of the string is less than set or
fixed-length then it is padded with extra memory
space.
In VARCHAR, If the length of the string is less than
the set or fixed-length then it will store as it is
without padded with extra memory spaces.
3. CHAR stands for “Character” VARCHAR stands for “Variable Character”
4. Storage size of CHAR datatypes is equal to n bytes i.e.
set length.
The storage size of the VARCHAR datatype is equal
to the actual length of the entered string in bytes.
5. We should use the CHAR datatype when we expect
the data values in a column are of the same length.
We should use the VARCHAR datatype when we
expect the data values in a column are of variable
length.
6. CHAR takes 1 byte for each character.
VARCHAR takes 1 byte for each character and some
extra bytes for holding length information.
9. Better performance than VARCHAR. Performance is not good as compared to
CHAR.
Database Commands in MySql :
Security : Its Databases are secured & protected with password.
Getting listings of available databases
mysql> SHOW DATABASES;
Creating a database (DDL)
mysql> CREATE database myschool;
mysql> SHOW DATABASES;
Deleting a database (DDL)
mysql> DROP database;
After database creation we can open the database using USE
command
mysql> USE myschool;
The command DESCRIBE is used to view the structure of a table.
mysql> DESCRIBE/desc student;
To insert new rows into an existing table use the
INSERT command: (DML)
mysql> INSERT INTO student values(‘Ram ’,’Kumar’,’Udaipur’,’4’);
We can insert record with specific column only :
mysql> INSERT INTO student(lastname,firstname,city) values(‘dwivedi’,’Mohak’,’Udaipur’);
Inserting NULL Values :
• To Insert NULL in a specific column , you can type NULL without quotes .
Eg :
insert into student values("Kishore","Ram","Ooty",null);
SELECT command : (DML)
• With the SELECT command we can retrieve previously inserted rows:
A general form of SELECT is:
SELECT what to select(field name) FROM table(s) WHERE condition
that the data must satisfy;
• Comparison operators are: < ; <= ; = ; != or <> ; >= ; >
• Logical operators are: AND ; OR ; NOT
• Comparison operator for special value NULL: IS
Eliminating Redundant Data - distinct
• To display data after removal of duplicate values from specific column.
mysql> select distinct last_name from student;
Select Specific Rows – WHERE clause
• In real life , tables can contain unlimited rows.
• There is no need to view all the rows when only certain rows are
needed .
• The WHERE clause is used to filter records.
• It is used to extract only those records that fulfill a specified condition.
Note: The WHERE clause is not only used in SELECT statements,
it is also used in UPDATE, DELETE, etc.!
The following operators can be used in the WHERE clause:
Scalar Expressions with Selected FIelds :
If you want to perform simple numeric computations on the data.
Example :
SELECT salesman_name,comm*100 FROM salesman;
Using Column ALiases :
Example :
SELECT EName as “Name” FROM EMPLOYEE;
SELECT date,type as “event_type” FROM event;
SELECT Ename AS ‘Name’, Salary*12 AS 'Annual Income’ FROM EMPLOYEE;
Selecting rows by using the WHERE clause in the SELECT
command
mysql> SELECT * FROM student WHERE class=“4";
Selecting specific columns(Projection) by listing their names
mysql> SELECT first_name, class FROM student;
Logical Operators :
• The logical operators OR(||) / in , AND(&&) / between(Range of values) ,
NOT(!) are used to connect search conditions in the where clause .
Eg:
SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country =
'India’;
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%’;
SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country =
'India’;
BETWEEN- to access data in specified range
mysql> select * from student where class between 4 and 6;
(or)
mysql>select * from student where class>=4 and class<=6;
IN- operator allows us to easily test if the expression in the list of values :
mysql> select * from Student where class in (4,5,6);
(or)
mysql> select * from student where class=4 or class=5 or class=6;
Selecting rows with null values in specific column :
mysql> SELECT * FROM Student WHERE Class IS NULL ;
Note: A NULL value is different from a zero value or a field that contains spaces. A field
with a NULL value is one that has been left blank during record creation!
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
Any arithmetic expression containing a null always evaluates to null.For
example ,null added to 10 is null ,In fact all operators return null when given a null
operand . (Except concatenation) eg : 5 + NULL = NULL
Pattern Matching – LIKE Operator
• A string pattern can be used in SQL using the following wild card characters :
% - Represents a substring in any length
_ - Represents a single character
Example:
‘A%’ represents any string starting with ‘A’ character.
‘_ _A’ represents any 3 character string ending with ‘A’.
‘_B%’ represents any string having second character ‘B’
‘_ _ _’ represents any 3 letter string.
• A pattern can be used with LIKE operator.
• mysql> SELECT * FROM Student WHERE Name LIKE ‘A%’;
• mysql> SELECT * FROM Student WHERE Name LIKE ’%Singh%’;
• mysql> SELECT Name, City FROM Student WHERE Class>=8 AND Name LIKE ‘%Kumar%’ ;
Sorting results– order by clause :
• The ORDER BY command is used to sort the result set in
ascending or descending order.
• The ORDER BY command sorts the result set in ascending order
by default.
• To sort the records in descending order, use the DESC keyword.
Eg :
SELECT * FROM Customers ORDER BY CustomerName;
SELECT * FROM Customers ORDER BY CustomerName ASC;
SELECT * FROM Customers ORDER BY CustomerName DESC;
What is the sequence of commands in SQL?
• Six Operations to Order:
SELECT,
FROM,
WHERE,
GROUP BY,
HAVING,
ORDER BY.
Modify data with UPDATE Command : (DML)
• The UPDATE statement in SQL is used to update the data of an
existing table in the database using set keyword.
UPDATE Customer SET
CustomerName = 'Nitin’
WHERE Age = 22;
Updating Multiple Columns :
Update the columns NAME to ‘Satyam’ and Country to ‘USA’ where
CustomerID is 1.
Eg :
UPDATE Customer SET CustomerName = 'Satyam',Country = 'USA' WHERE CustomerID =
1;
* UPDATE Customer SET Age=age+2 WHERE (CustomerID = 1 or customerID = 4);
* UPDATE Customer SET Country = NULL WHERE CustomerID = 1;
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement.
The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all
records in the table will be updated!
Deleting Data with DELETE Command : (DML)
SQL DELETE is a basic SQL operation used to delete data in a database.
SQL DELETE is an important part of database management DELETE can be used
to selectively remove records from a database table based on certain conditions.
DELETE FROM GFG_Employees WHERE NAME = 'Rithvik’; #Single row
DELETE FROM GFG_Employees WHERE department = 'Development’; #Multiple
row
DELETE FROM GFG_EMPLOyees; # Delete all the records
More DDL Commands :
Alter Table command(DDL) :
The ALTER TABLE statement in SQL is used to add, remove, or
modify columns in an existing table.
Adding
Columns
Modifying
Column
Definitions
Removing
Table
Components
Alter Table command(DDL) : (Adding Columns)
Syntax :
ALTER TABLE table_name ADD column_name datatype;
Example :
ID LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
ID LastName FirstName Address City DateOfBirth
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
ALTER TABLE persons ADD DateOfBirth varchar(255);
Modify datatype of an attribute :
Syntax:
ALTER TABLE table_name MODIFY attribute DATATYPE;
Suppose we need to change the size of the attribute GAddress from
VARCHAR(30) to VARCHAR(40) of the GUARDIAN table. The MySQL
statement will be:
Example :
ALTER TABLE student MODIFY town VARCHAR(20) [first|after column];
(Modifying Order of Column )
Changing a Column Name:
Syntax :
Alter table <tablename> change column old_column_name
new_column_name column definition ;
Example :
Alter table student change column city town varchar(20) ;
Remove an attribute :
Syntax : ALTER TABLE table_name DROP column attribute;
Example : ALTER TABLE GUARDIAN DROP column income;
Remove primary key from the table :
Syntax: ALTER TABLE table_name DROP PRIMARY KEY;
Example : ALTER TABLE GUARDIAN DROP PRIMARY KEY;
The Drop Table Command :
Syntax : Drop table [if exists] <tablename> ;
Example : Drop table student;
Example : Drop database school;
DROP DELETE TRUNCATE
Definition It completely removes the
table from the database.
It removes one or more records
from the table.
It removes all the rows from
the existing table
Type of
Command
It is a DDL command It is a DML command It is a DDL command
Syntax DROP TABLE table_name; DELETE FROM table_namee
WHERE conditions;
TRUNCATE TABLE
table_name;
Memory
Management
It completely removes the
allocated space for the table
from memory.
It doesn’t free the allocated space
of the table.
It doesn’t free the allocated
space of the table.
Effect on Table Removes the entire table
structure.
Doesn’t affect the table structure Doesn’t affect the table
structure
Speed and
Performance
It is faster than DELETE but
slower than TRUNCATE as it
firstly deletes the rows and
then the table from the
database.
It is slower than the DROP and
TRUNCATE commands as it
deletes one row at a time based on
the specified conditions.
It is faster than both the
DELETE and DROP
commands as it deletes all the
records at a time without any
condition.
Use with
WHERE clause
Not applicable as it operates
on the entire table
Can be used It can’t be used as it is
applicable to the entire table
Difference Between DROP DELETE and TRUNCATE: DROP vs DELETE vs TRUNCATE
Data Integrity Through Constraints :
In DBMS, Integrity constraints can be defined as a set of rules that are used
to maintain the information’s quality.
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement.
Two basic types of constraints are :
*Column Constraints - Apply only to the individual
columns.
*Table COnstraints - Apply to groups of one or
more columns.
Syntax :
create table <tablename>
( <column name> <data type> [(size)]<column constraint>,
<column name> <data type> [(size)]<column constraint>,
<table constraint>(<column name>,[,<column name>...])...);
Types of constraints:
● Unique Constraints - Ensures that all values in a column are different
● Primary Key Constraints - A combination of a NOT NULL and UNIQUE.
● Not Null Constraints - Ensures that a column cannot have a NULL value
● Foreign Key Constraints - Prevents actions that would destroy links between tables
● Default Constraints - Sets a default value for a column if no value is specified
● Check Constraints - Ensures that the values in a column satisfies a specific condition
Example :
create table employee
( ecode integer NOT NULL UNIQUE ,
ename char(20) NOT NULL,
aadhaar_no integer PRIMARY KEY ,
gross_sal decimal );
Syntax For Foreign Key Constraint :
create table items
( itemno char(5) NOT NULL PRIMARY KEY,
.
.
);
create table orders
( orderno integer PRIMARY KEY,
.
.
itemno char(5) REFERENCES items(itemno) —-------------> Foreign Key
);
ON DELETE CASCADE & ON UPDATE CASCADE:
ON DELETE CASCADE constraint is used in MySQL to delete the rows from the
child table automatically, when the rows from the parent table are deleted.
ON UPDATE CASCADE clause in MySQL is used to update the matching records
from the child table automatically when we update the rows in the parent
table.
1. CREATE TABLE Payment (
2. payment_id integer PRIMARY KEY NOT NULL,
3. emp_id integer NOT NULL,
4. amount decimal NOT NULL,
5. payment_date date NOT NULL,
6. emp_id integer REFERENCES Employee (emp_id) ON DELETE CASCADE ON UPDATE CASCADE
7. );
Alter Table command(DDL) : (Constraint)
Add a primary key data constraint on the column id :
• ALTER TABLE persons ADD primary key(id);
Add foreign key to a relation :
Syntax: ALTER TABLE table_name ADD FOREIGN KEY(attribute name)
REFERENCES referenced_table_name (attribute name);
Example : ALTER TABLE STUDENT ADD FOREIGN KEY(GUID)
REFERENCES GUARDIAN(GUID);
Add constraint UNIQUE to an existing attribute :
Syntax: ALTER TABLE table_name ADD UNIQUE (attribute name);
Example : ALTER TABLE GUARDIAN ADD UNIQUE(GPhone);
Modify constraint of an attribute :
When we create a table, by default each attribute takes NULL value
except for the attribute defined as primary key. We can change an
attribute’s constraint from NULL to NOT NULL using an alter statement.
Syntax:
ALTER TABLE table_name MODIFY attribute DATATYPE NOT NULL;
Example :
ALTER TABLE STUDENT MODIFY SName VARCHAR(20) NOT NULL;
Let’s Practice
Employee Table :
Retrieve selected columns :
mysql> SELECT EmpNo FROM EMPLOYEE;
mysql>SELECT EmpNo, Ename FROM EMPLOYEE;
Renaming of columns :
mysql> SELECT EName as “Name” FROM EMPLOYEE;
Select names of all employees along with their annual income (calculated as
Salary*12). While displaying the query result, rename the column EName as
Name.
mysql> SELECT EName as “Name”, Salary*12 FROM EMPLOYEE;
DISTINCT Clause :
mysql> SELECT DISTINCT DeptId FROM EMPLOYEE;
WHERE Clause :
mysql> SELECT DISTINCT Salary -> FROM EMPLOYEE -> WHERE Deptid='D01';
Display all the details of those employees of D04 department who earn more
than 5000.
mysql> SELECT * FROM EMPLOYEE -> WHERE Salary > 5000 AND DeptId = 'D04';
The following query selects records of all the employees except
Aaliya.
mysql> SELECT * FROM EMPLOYEE WHERE NOT Ename = 'Aaliya';
The following query selects the name and department number of all those employees
who are earning salary between 20000 and 50000 (both values inclusive).
mysql> SELECT Ename, DeptId FROM EMPLOYEE WHERE Salary>=20000 AND
Salary<=50000;
The query in example 9.6 defines a range that can also be checked using a
comparison operator BETWEEN, as shown below:
mysql> SELECT Ename, DeptId -> FROM EMPLOYEE -> WHERE Salary BETWEEN
20000 AND 50000;
The following query selects details of all the employees who work in the
departments having deptid D01, D02 or D04.
mysql> SELECT * FROM EMPLOYEE WHERE DeptId = 'D01' OR DeptId = 'D02' OR
DeptId = 'D04';
The above query can be rewritten using IN operator as shown below:
mysql> SELECT * FROM EMPLOYEE -> WHERE DeptId IN ('D01', 'D02' , 'D04');
The following query selects details of all the employees except those working in department number D01 or D02.
mysql> SELECT * FROM EMPLOYEE WHERE DeptId NOT IN('D01', 'D02');
Note: Here we need to combine NOT with IN as we want to retrieve all records
except with DeptId D01 and D02.
ORDER BY Clause :
The following query selects details of all the employees
in ascending order of their salaries
mysql> SELECT * FROM EMPLOYEE ORDER BY Salary;
Select details of all the employees in descending order of
their salaries.
mysql> SELECT * FROM EMPLOYEE -> ORDER BY Salary DESC;
Handling NULL Values :
The following query selects details of all those employees who have not been
given a bonus. This implies that the bonus column will be blank.
mysql> SELECT * FROM EMPLOYEE WHERE Bonus IS NULL;
The following query selects names of all employees who have been given a
bonus (i.e., Bonus is not null) and works in the department D01.
mysql> SELECT EName FROM EMPLOYEE WHERE Bonus IS NOT NULL AND
DeptID = ‘D01’;
Substring pattern matching :
The following query selects details of all those employees whose name
starts with 'K'.
mysql> SELECT * FROM EMPLOYEE WHERE Ename like 'K%';
The following query selects details of all those employees whose name
ends with 'a', and gets a salary more than 45000.
mysql> SELECT * FROM EMPLOYEE WHERE Ename like '%a' -> AND Salary >
45000;
The following query selects details of all those employees whose name
consists of exactly 5 letters and starts with any letter but has ‘ANYA’ after that.
mysql> SELECT * FROM EMPLOYEE WHERE Ename like '_ANYA';
The following query selects names of all employees containing 'se' as a substring
in name.
mysql> SELECT Ename FROM EMPLOYEE -> WHERE Ename like '%se%';
The following query selects names of all employees containing 'a'
as the second character.
mysql> SELECT EName FROM EMPLOYEE -> WHERE Ename like '_a%';
Unit 10 - Realtional Databases.pptxxxxxxxxx
Unit 10 - Realtional Databases.pptxxxxxxxxx
Unit 10 - Realtional Databases.pptxxxxxxxxx
Unit 10 - Realtional Databases.pptxxxxxxxxx
Unit 10 - Realtional Databases.pptxxxxxxxxx
Unit 10 - Realtional Databases.pptxxxxxxxxx

More Related Content

PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Relational Database.pptx
PPTX
PPTX
Ch-11 Relational Databases.pptx
PPTX
IP-Lesson_Planning(Unit4 - Database concepts and SQL).pptx
PPTX
DATABASE-1.pptx
PPTX
Data Manipulation ppt. for BSIT students
PDF
DBMS unit-3.pdf
MYSQL Presentation for SQL database connectivity
Relational Database.pptx
Ch-11 Relational Databases.pptx
IP-Lesson_Planning(Unit4 - Database concepts and SQL).pptx
DATABASE-1.pptx
Data Manipulation ppt. for BSIT students
DBMS unit-3.pdf

Similar to Unit 10 - Realtional Databases.pptxxxxxxxxx (20)

PPT
Module02
PPTX
SQL things ace series of the thing useful
PDF
Data Base Management System.pdf
PPTX
SQL SERVER Training in Pune Slides
PPTX
unit-ii.pptx
PPTX
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
PPTX
DBMS Part-3.pptx
PPTX
SQL for interview
PPTX
Complete first chapter rdbm 17332
PPTX
SQL_all_commnads_aggregate_functions.pptx
PPTX
DB2 on Mainframe
PDF
Lecture on DBMS & MySQL.pdf v. C. .
PPTX
Relational Database Management System
PDF
Oracle
PDF
databases management system and other DBA1 نظري.pdf
PDF
SQL Complete Tutorial. All Topics Covered
PPTX
Using Basic Structured Query Language lo1.pptx
PPTX
T-SQL Overview
PPTX
Pl sql content
Module02
SQL things ace series of the thing useful
Data Base Management System.pdf
SQL SERVER Training in Pune Slides
unit-ii.pptx
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
DBMS Part-3.pptx
SQL for interview
Complete first chapter rdbm 17332
SQL_all_commnads_aggregate_functions.pptx
DB2 on Mainframe
Lecture on DBMS & MySQL.pdf v. C. .
Relational Database Management System
Oracle
databases management system and other DBA1 نظري.pdf
SQL Complete Tutorial. All Topics Covered
Using Basic Structured Query Language lo1.pptx
T-SQL Overview
Pl sql content
Ad

Recently uploaded (20)

PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Institutional Correction lecture only . . .
PPTX
master seminar digital applications in india
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Insiders guide to clinical Medicine.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
Pre independence Education in Inndia.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
FourierSeries-QuestionsWithAnswers(Part-A).pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Institutional Correction lecture only . . .
master seminar digital applications in india
Renaissance Architecture: A Journey from Faith to Humanism
PPH.pptx obstetrics and gynecology in nursing
Insiders guide to clinical Medicine.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial diseases, their pathogenesis and prophylaxis
O5-L3 Freight Transport Ops (International) V1.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Complications of Minimal Access Surgery at WLH
Pre independence Education in Inndia.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Ad

Unit 10 - Realtional Databases.pptxxxxxxxxx

  • 2. Database : • A collection of data is referred to as database and a database(management)system is basically a computer based record keeping system. • It maintains any information that may be necessary to the decision-making involved in the management of the organization. • The intention of a database is that the same collection of data should serve as many applications as possible. • Database would permit not only the retrieval of data but also continuous modification of data needed for control of operations.
  • 3. • A traditional file processing system suffers from some major limitations like - data redundancy, - data inconsistency , - unsharable data , - unstandardized data , - insecure data… • On the other hand , a database system overcomes all these limitations and ensure continues efficiency.. • The advantages provided by a database system are : - Reduced data redundancy - Controlled data inconsistency - Shared data - Standardized data - Secured data (Unauthorized access is not restricted)
  • 4. Relational Database Model : • Different types of DBMS are available and their classification is done based on the underlying data model. • The most commonly used data model is Relational Data Model. • Other types of data models include - object-oriented data model, -Network data model, - document model, - hierarchical data model.
  • 5. Relational Database Model : • In relational model, tables are called relations.
  • 7. The commonly used terminologies in relational data model : i) ATTRIBUTE: The columns of a relation are the attributes which are also referred as fields. For example, GUID, GName, GPhone and GAddress are attributes of relation GUARDIAN. ii) TUPLE: Each row of data in a relation (table) is called a tuple. iii) DOMAIN: It is collection of values from which the value is derived for a column. Usually, a data type is used to specify domain for an attribute. For example, in STUDENT relation, the attribute RollNumber takes integer values and hence its domain is a set of integer values. Similarly, the set of character strings constitutes the domain of the attribute SName. iv) DEGREE: The number of attributes in a relation is called the Degree of the relation. v) CARDINALITY: The number of tuples in a relation is called the Cardinality of the relation.
  • 9. Properties of a Relation : ▪ Atomicity : Each column assigned a unique name and must have atomic(indivisible) value i.e. a value that can not be further subdivided. ▪ No duplicity: No two rows of relation will be identical i.e. in any two rows value in at least one column must be different. ▪ All items in a column are homogeneous i.e.same data type. ▪ Ordering of rows and column is immaterial.
  • 10. SQL • SQL is an acronym of Structured Query Language • It is a standard language developed and used for accessing and modifying relational databases. • The SQL language was originally developed at the IBM research laboratory in San José. • SQL is being used by many database management systems. Some of them are: • ➢MySQL • ➢PostgreSQL • ➢Oracle • ➢SQLite • ➢Microsoft SQL Server
  • 11. Views • A view is a kind of table whose contents are taken from other tables depending upon a condition. • View does not contain data of their own. • A view is a (virtual) table that does not really exist in its own right but instead derived from one or more underlying base tables . Eg : create view gooditems as select * from items where price>12; Itemno Itemname Price I1 Milk bread 15.00 I4 Ice cream 16.00 i7 Cake 20.00 Itemno Itemname Price I1 Milk bread 15.00 I2 Cream Biscuit 12.00 I4 Ice cream 16.00 I5 Cold drink 10.00 I7 Cake 20.00
  • 12. KEYS IN A DATABASE : • Key plays an important role in relational database; it is used for identifying unique rows from table & establishes relationship among tables on need. Types of keys in DBMS : Primary Key – A primary is a column or set of columns in a table that uniquely identifies tuples in that table. Primary keys must contain UNIQUE values, and cannot contain NULL values. Primary Key Itemno Itemname Price I1 Milk bread 15.00 I2 Cream Biscuit 12.00 I4 Ice cream 16.00 I5 Cold drink 10.00 I7 Cake 20.00
  • 13. KEYS IN A DATABASE : Composite Primary Key - Combination of more than one attribute provides a unique value for each row .The primary key consists of more than one attribute , it is called composite primary key .
  • 14. KEYS IN A DATABASE : • Candidate Key –It is an attribute or a set of attributes or keys participating for Primary Key, to uniquely identify each record in that table. • Alternate Key – Out of all candidate keys, only one gets selected as primary key, remaining keys are known as alternate or secondary keys. • Foreign Key –A non-key attribute , whose values are derived from the primary key of some other table , is known as Foreign key in its current table. • Referential Integrity – It is system of rules that a DBMS uses to ensure that relationships between records in related tables are valid , and that users don’t accidentally delete or change related data.
  • 16. Key features of MYSQL are : • Open Source & Free of Cost: It is Open Source and available at free of cost. • Portability: Small enough in size to instal and run it on any types of Hardware and OS like Linux,MS Windows or Mac etc. • Security : Its Databases are secured & protected with password. • Connectivity : Various APIs are developed to connect it with many programming languages. • Query Language : It supports SQL (Structured Query Language) for handling database. • Data Types : It provides many data types to support different types of data .
  • 17. Classification Of SQL statements : • DDL (Data Definition Language) - To create database and table structure-commands like CREATE , ALTER , DROP etc. • DML (Data Manipulation Language) - Record/rows related operations.commands like SELECT...., INSERT..., DELETE..., UPDATE.... etc. • DCL (Data Control Language) - used to manipulate permissions or access rights to the tables. commands like GRANT , REVOKE etc. • Transactional control Language - Used to control the transactions.commands like COMMIT, ROLLBACK, SAVEPOINT etc
  • 18. Difference between DDL and DML : DDL DML It stands for Data Definition Language. It stands for Data Manipulation Language. It is used to create database schema and can be used to define some constraints as well. It is used to add, retrieve, or update the data. It basically defines the column (Attributes) of the table. It adds or updates the row of the table. These rows are called tuples. Basic commands present in DDL are CREATE, DROP, RENAME, ALTER, etc. BASIC commands present in DML are UPDATE, INSERT etc. DDL does not use WHERE clause in its statement. While DML uses WHERE clause in its statement. DDL is used to define the structure of a database. DML is used to manipulate the data within the database. DDL statements are typically executed less frequently than DML statement DML statements are frequently executed to manipulate and query data. DDL statements are not used to manipulate data directly. DML statements are used to manipulate data directly. Examples of DDL commands: CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE TABLE, and RENAME TABLE. Examples of DML commands: SELECT, INSERT, UPDATE, DELETE .
  • 19. Data type in MySQL : • Numeric Data Types: INTEGER or INT – up to 11 digit number without decimal. SMALLINT – up to 5 digit number without decimal. FLOAT (M,D) or DECIMAL(M,D) or NUMERIC(M,D) Stores Real numbers upto M digit length (including .) with D decimal places. e.g. Float (10,2) can store 1234567.89 • Date & Time Data Types: DATE - Stores date in YYYY-MM-DD format. TIME - Stores time in HH:MM:SS format. • String or Text Data Type: CHAR(Size) A fixed length string up to 255 characters. (default is 1) VARCHAR(Size):A variable length string up to 255 characters.
  • 20. Difference between Char and Varchar : S.no CHAR VARCHAR 1. CHAR datatype is used to store character strings of fixed length. VARCHAR datatype is used to store character strings of variable length. 2. In CHAR, If the length of the string is less than set or fixed-length then it is padded with extra memory space. In VARCHAR, If the length of the string is less than the set or fixed-length then it will store as it is without padded with extra memory spaces. 3. CHAR stands for “Character” VARCHAR stands for “Variable Character” 4. Storage size of CHAR datatypes is equal to n bytes i.e. set length. The storage size of the VARCHAR datatype is equal to the actual length of the entered string in bytes. 5. We should use the CHAR datatype when we expect the data values in a column are of the same length. We should use the VARCHAR datatype when we expect the data values in a column are of variable length. 6. CHAR takes 1 byte for each character. VARCHAR takes 1 byte for each character and some extra bytes for holding length information. 9. Better performance than VARCHAR. Performance is not good as compared to CHAR.
  • 21. Database Commands in MySql : Security : Its Databases are secured & protected with password.
  • 22. Getting listings of available databases mysql> SHOW DATABASES;
  • 23. Creating a database (DDL) mysql> CREATE database myschool; mysql> SHOW DATABASES;
  • 24. Deleting a database (DDL) mysql> DROP database;
  • 25. After database creation we can open the database using USE command mysql> USE myschool;
  • 26. The command DESCRIBE is used to view the structure of a table. mysql> DESCRIBE/desc student;
  • 27. To insert new rows into an existing table use the INSERT command: (DML) mysql> INSERT INTO student values(‘Ram ’,’Kumar’,’Udaipur’,’4’);
  • 28. We can insert record with specific column only : mysql> INSERT INTO student(lastname,firstname,city) values(‘dwivedi’,’Mohak’,’Udaipur’);
  • 29. Inserting NULL Values : • To Insert NULL in a specific column , you can type NULL without quotes . Eg : insert into student values("Kishore","Ram","Ooty",null);
  • 30. SELECT command : (DML) • With the SELECT command we can retrieve previously inserted rows: A general form of SELECT is: SELECT what to select(field name) FROM table(s) WHERE condition that the data must satisfy; • Comparison operators are: < ; <= ; = ; != or <> ; >= ; > • Logical operators are: AND ; OR ; NOT • Comparison operator for special value NULL: IS
  • 31. Eliminating Redundant Data - distinct • To display data after removal of duplicate values from specific column. mysql> select distinct last_name from student;
  • 32. Select Specific Rows – WHERE clause • In real life , tables can contain unlimited rows. • There is no need to view all the rows when only certain rows are needed . • The WHERE clause is used to filter records. • It is used to extract only those records that fulfill a specified condition. Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
  • 33. The following operators can be used in the WHERE clause:
  • 34. Scalar Expressions with Selected FIelds : If you want to perform simple numeric computations on the data. Example : SELECT salesman_name,comm*100 FROM salesman; Using Column ALiases : Example : SELECT EName as “Name” FROM EMPLOYEE; SELECT date,type as “event_type” FROM event; SELECT Ename AS ‘Name’, Salary*12 AS 'Annual Income’ FROM EMPLOYEE;
  • 35. Selecting rows by using the WHERE clause in the SELECT command mysql> SELECT * FROM student WHERE class=“4";
  • 36. Selecting specific columns(Projection) by listing their names mysql> SELECT first_name, class FROM student;
  • 37. Logical Operators : • The logical operators OR(||) / in , AND(&&) / between(Range of values) , NOT(!) are used to connect search conditions in the where clause . Eg: SELECT * FROM employee WHERE emp_city = 'Varanasi' OR emp_country = 'India’; SELECT * FROM employee WHERE emp_city NOT LIKE 'A%’; SELECT * FROM employee WHERE emp_city = 'Allahabad' AND emp_country = 'India’;
  • 38. BETWEEN- to access data in specified range mysql> select * from student where class between 4 and 6; (or) mysql>select * from student where class>=4 and class<=6;
  • 39. IN- operator allows us to easily test if the expression in the list of values : mysql> select * from Student where class in (4,5,6); (or) mysql> select * from student where class=4 or class=5 or class=6;
  • 40. Selecting rows with null values in specific column : mysql> SELECT * FROM Student WHERE Class IS NULL ; Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation! It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead. Any arithmetic expression containing a null always evaluates to null.For example ,null added to 10 is null ,In fact all operators return null when given a null operand . (Except concatenation) eg : 5 + NULL = NULL
  • 41. Pattern Matching – LIKE Operator • A string pattern can be used in SQL using the following wild card characters : % - Represents a substring in any length _ - Represents a single character Example: ‘A%’ represents any string starting with ‘A’ character. ‘_ _A’ represents any 3 character string ending with ‘A’. ‘_B%’ represents any string having second character ‘B’ ‘_ _ _’ represents any 3 letter string. • A pattern can be used with LIKE operator. • mysql> SELECT * FROM Student WHERE Name LIKE ‘A%’; • mysql> SELECT * FROM Student WHERE Name LIKE ’%Singh%’; • mysql> SELECT Name, City FROM Student WHERE Class>=8 AND Name LIKE ‘%Kumar%’ ;
  • 42. Sorting results– order by clause : • The ORDER BY command is used to sort the result set in ascending or descending order. • The ORDER BY command sorts the result set in ascending order by default. • To sort the records in descending order, use the DESC keyword. Eg : SELECT * FROM Customers ORDER BY CustomerName; SELECT * FROM Customers ORDER BY CustomerName ASC; SELECT * FROM Customers ORDER BY CustomerName DESC;
  • 43. What is the sequence of commands in SQL? • Six Operations to Order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY.
  • 44. Modify data with UPDATE Command : (DML) • The UPDATE statement in SQL is used to update the data of an existing table in the database using set keyword. UPDATE Customer SET CustomerName = 'Nitin’ WHERE Age = 22;
  • 45. Updating Multiple Columns : Update the columns NAME to ‘Satyam’ and Country to ‘USA’ where CustomerID is 1. Eg : UPDATE Customer SET CustomerName = 'Satyam',Country = 'USA' WHERE CustomerID = 1; * UPDATE Customer SET Age=age+2 WHERE (CustomerID = 1 or customerID = 4); * UPDATE Customer SET Country = NULL WHERE CustomerID = 1; Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!
  • 46. Deleting Data with DELETE Command : (DML) SQL DELETE is a basic SQL operation used to delete data in a database. SQL DELETE is an important part of database management DELETE can be used to selectively remove records from a database table based on certain conditions. DELETE FROM GFG_Employees WHERE NAME = 'Rithvik’; #Single row DELETE FROM GFG_Employees WHERE department = 'Development’; #Multiple row DELETE FROM GFG_EMPLOyees; # Delete all the records
  • 47. More DDL Commands : Alter Table command(DDL) : The ALTER TABLE statement in SQL is used to add, remove, or modify columns in an existing table. Adding Columns Modifying Column Definitions Removing Table Components
  • 48. Alter Table command(DDL) : (Adding Columns) Syntax : ALTER TABLE table_name ADD column_name datatype; Example : ID LastName FirstName Address City 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger ID LastName FirstName Address City DateOfBirth 1 Hansen Ola Timoteivn 10 Sandnes 2 Svendson Tove Borgvn 23 Sandnes 3 Pettersen Kari Storgt 20 Stavanger ALTER TABLE persons ADD DateOfBirth varchar(255);
  • 49. Modify datatype of an attribute : Syntax: ALTER TABLE table_name MODIFY attribute DATATYPE; Suppose we need to change the size of the attribute GAddress from VARCHAR(30) to VARCHAR(40) of the GUARDIAN table. The MySQL statement will be: Example : ALTER TABLE student MODIFY town VARCHAR(20) [first|after column]; (Modifying Order of Column )
  • 50. Changing a Column Name: Syntax : Alter table <tablename> change column old_column_name new_column_name column definition ; Example : Alter table student change column city town varchar(20) ;
  • 51. Remove an attribute : Syntax : ALTER TABLE table_name DROP column attribute; Example : ALTER TABLE GUARDIAN DROP column income; Remove primary key from the table : Syntax: ALTER TABLE table_name DROP PRIMARY KEY; Example : ALTER TABLE GUARDIAN DROP PRIMARY KEY; The Drop Table Command : Syntax : Drop table [if exists] <tablename> ; Example : Drop table student; Example : Drop database school;
  • 52. DROP DELETE TRUNCATE Definition It completely removes the table from the database. It removes one or more records from the table. It removes all the rows from the existing table Type of Command It is a DDL command It is a DML command It is a DDL command Syntax DROP TABLE table_name; DELETE FROM table_namee WHERE conditions; TRUNCATE TABLE table_name; Memory Management It completely removes the allocated space for the table from memory. It doesn’t free the allocated space of the table. It doesn’t free the allocated space of the table. Effect on Table Removes the entire table structure. Doesn’t affect the table structure Doesn’t affect the table structure Speed and Performance It is faster than DELETE but slower than TRUNCATE as it firstly deletes the rows and then the table from the database. It is slower than the DROP and TRUNCATE commands as it deletes one row at a time based on the specified conditions. It is faster than both the DELETE and DROP commands as it deletes all the records at a time without any condition. Use with WHERE clause Not applicable as it operates on the entire table Can be used It can’t be used as it is applicable to the entire table Difference Between DROP DELETE and TRUNCATE: DROP vs DELETE vs TRUNCATE
  • 53. Data Integrity Through Constraints : In DBMS, Integrity constraints can be defined as a set of rules that are used to maintain the information’s quality. Constraints can be specified when the table is created with the CREATE TABLE statement, or after the table is created with the ALTER TABLE statement. Two basic types of constraints are : *Column Constraints - Apply only to the individual columns. *Table COnstraints - Apply to groups of one or more columns. Syntax : create table <tablename> ( <column name> <data type> [(size)]<column constraint>, <column name> <data type> [(size)]<column constraint>, <table constraint>(<column name>,[,<column name>...])...);
  • 54. Types of constraints: ● Unique Constraints - Ensures that all values in a column are different ● Primary Key Constraints - A combination of a NOT NULL and UNIQUE. ● Not Null Constraints - Ensures that a column cannot have a NULL value ● Foreign Key Constraints - Prevents actions that would destroy links between tables ● Default Constraints - Sets a default value for a column if no value is specified ● Check Constraints - Ensures that the values in a column satisfies a specific condition Example : create table employee ( ecode integer NOT NULL UNIQUE , ename char(20) NOT NULL, aadhaar_no integer PRIMARY KEY , gross_sal decimal );
  • 55. Syntax For Foreign Key Constraint : create table items ( itemno char(5) NOT NULL PRIMARY KEY, . . ); create table orders ( orderno integer PRIMARY KEY, . . itemno char(5) REFERENCES items(itemno) —-------------> Foreign Key );
  • 56. ON DELETE CASCADE & ON UPDATE CASCADE: ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. ON UPDATE CASCADE clause in MySQL is used to update the matching records from the child table automatically when we update the rows in the parent table. 1. CREATE TABLE Payment ( 2. payment_id integer PRIMARY KEY NOT NULL, 3. emp_id integer NOT NULL, 4. amount decimal NOT NULL, 5. payment_date date NOT NULL, 6. emp_id integer REFERENCES Employee (emp_id) ON DELETE CASCADE ON UPDATE CASCADE 7. );
  • 57. Alter Table command(DDL) : (Constraint) Add a primary key data constraint on the column id : • ALTER TABLE persons ADD primary key(id); Add foreign key to a relation : Syntax: ALTER TABLE table_name ADD FOREIGN KEY(attribute name) REFERENCES referenced_table_name (attribute name); Example : ALTER TABLE STUDENT ADD FOREIGN KEY(GUID) REFERENCES GUARDIAN(GUID); Add constraint UNIQUE to an existing attribute : Syntax: ALTER TABLE table_name ADD UNIQUE (attribute name); Example : ALTER TABLE GUARDIAN ADD UNIQUE(GPhone);
  • 58. Modify constraint of an attribute : When we create a table, by default each attribute takes NULL value except for the attribute defined as primary key. We can change an attribute’s constraint from NULL to NOT NULL using an alter statement. Syntax: ALTER TABLE table_name MODIFY attribute DATATYPE NOT NULL; Example : ALTER TABLE STUDENT MODIFY SName VARCHAR(20) NOT NULL;
  • 61. Retrieve selected columns : mysql> SELECT EmpNo FROM EMPLOYEE;
  • 62. mysql>SELECT EmpNo, Ename FROM EMPLOYEE;
  • 63. Renaming of columns : mysql> SELECT EName as “Name” FROM EMPLOYEE;
  • 64. Select names of all employees along with their annual income (calculated as Salary*12). While displaying the query result, rename the column EName as Name. mysql> SELECT EName as “Name”, Salary*12 FROM EMPLOYEE;
  • 65. DISTINCT Clause : mysql> SELECT DISTINCT DeptId FROM EMPLOYEE; WHERE Clause : mysql> SELECT DISTINCT Salary -> FROM EMPLOYEE -> WHERE Deptid='D01';
  • 66. Display all the details of those employees of D04 department who earn more than 5000. mysql> SELECT * FROM EMPLOYEE -> WHERE Salary > 5000 AND DeptId = 'D04'; The following query selects records of all the employees except Aaliya. mysql> SELECT * FROM EMPLOYEE WHERE NOT Ename = 'Aaliya';
  • 67. The following query selects the name and department number of all those employees who are earning salary between 20000 and 50000 (both values inclusive). mysql> SELECT Ename, DeptId FROM EMPLOYEE WHERE Salary>=20000 AND Salary<=50000; The query in example 9.6 defines a range that can also be checked using a comparison operator BETWEEN, as shown below: mysql> SELECT Ename, DeptId -> FROM EMPLOYEE -> WHERE Salary BETWEEN 20000 AND 50000;
  • 68. The following query selects details of all the employees who work in the departments having deptid D01, D02 or D04. mysql> SELECT * FROM EMPLOYEE WHERE DeptId = 'D01' OR DeptId = 'D02' OR DeptId = 'D04'; The above query can be rewritten using IN operator as shown below: mysql> SELECT * FROM EMPLOYEE -> WHERE DeptId IN ('D01', 'D02' , 'D04');
  • 69. The following query selects details of all the employees except those working in department number D01 or D02. mysql> SELECT * FROM EMPLOYEE WHERE DeptId NOT IN('D01', 'D02'); Note: Here we need to combine NOT with IN as we want to retrieve all records except with DeptId D01 and D02.
  • 70. ORDER BY Clause : The following query selects details of all the employees in ascending order of their salaries mysql> SELECT * FROM EMPLOYEE ORDER BY Salary;
  • 71. Select details of all the employees in descending order of their salaries. mysql> SELECT * FROM EMPLOYEE -> ORDER BY Salary DESC;
  • 72. Handling NULL Values : The following query selects details of all those employees who have not been given a bonus. This implies that the bonus column will be blank. mysql> SELECT * FROM EMPLOYEE WHERE Bonus IS NULL;
  • 73. The following query selects names of all employees who have been given a bonus (i.e., Bonus is not null) and works in the department D01. mysql> SELECT EName FROM EMPLOYEE WHERE Bonus IS NOT NULL AND DeptID = ‘D01’;
  • 74. Substring pattern matching : The following query selects details of all those employees whose name starts with 'K'. mysql> SELECT * FROM EMPLOYEE WHERE Ename like 'K%'; The following query selects details of all those employees whose name ends with 'a', and gets a salary more than 45000. mysql> SELECT * FROM EMPLOYEE WHERE Ename like '%a' -> AND Salary > 45000;
  • 75. The following query selects details of all those employees whose name consists of exactly 5 letters and starts with any letter but has ‘ANYA’ after that. mysql> SELECT * FROM EMPLOYEE WHERE Ename like '_ANYA'; The following query selects names of all employees containing 'se' as a substring in name. mysql> SELECT Ename FROM EMPLOYEE -> WHERE Ename like '%se%';
  • 76. The following query selects names of all employees containing 'a' as the second character. mysql> SELECT EName FROM EMPLOYEE -> WHERE Ename like '_a%';