Database
Database
DBMS:
➢ A DBMS refers to Database Management System
➢ It is a software that is responsible for storing, manipulating, maintaining and utilizing
database.
➢ A database along with a DBMS is referred to as a database system.
➢ There are various DBMS software available in the market like :- Oracle, MS SQL Server,
MySQL, Sybase, PostgreSQL, SQLite
Purpose of DBMS:
➢ Reduced Data redundancy –
➢ Control Data Inconsistency
➢ Sharing of data
➢ Ensure data integrity
➢ Enforce standard
Component of a table:
➢ Byte: group of 8 bits and is used to store a character.Data Item: smallest unit of named
data. It represent one type of information and oftenreferred to as a field or column
information
➢ Record : collection of data items which represent a complete unit of information
➢ Table: collection of all Rows and Columns.
Common RDBMS:
➢ Oracle, MS SQL Server, MySQL, IBM DB2, IBM Informix, SAP Sybase, Adaptive
Server Enterprise, SAP Sybase IQ, Teradata, PostgreSQL, SQLite, etc.
➢ Out of these MySQL, PostgreSQL and SQLite are Open source implementation.
MySQL
➢ Runs on virtually all platforms including Linux, Unix and Windows. Popular for web based
application and online publishing. It is a part of LAMP (Linux, Apache, MySQL, PHP)
stack
SQLite
➢ Relational DBMS but it is not client-server database engine rather, it is embedded into end
program. Arguably the most widely deployed database engine as it is used by several
browsers, OS and embedded systems (Mobiles).
PostgreSQL
➢ General purpose object-relational DBMS.
➢ It is the most advanced open source database system. It is free and open source i.e. source
code is available under PostgreSQL license, a liberal open source license.
Various Terms Used in Relational Model: - A relational database is a type of database that
stores and provides access to data points that are related to one another.
Concept of Keys
➢ In relation each record must be unique i.e. no two identical records are allowed in the
Database.
➢ A key attribute identifies the record and must have unique values. There are various types
of Keys:
Primary Key:
➢ A set of one or more attribute that can identify a record uniquely in the relation is called
Primary Key.
➢ There can be only 1 primary key in a table
➢ Allows only distinct (no duplicate) values and also forces mandatory entry (NOT NULL)
i.e. we cannot left it blank.
Candidate Key
➢ In a table there can be more than one attribute which contains unique values. These
columns are known as candidate key as they are the candidate for primary key.
➢ Among these database analyst select one as a primary key based on requirement like must
contain unique value, compulsory entry and where maximum searching is done etc.
Alternate Key
➢ In case of multiple candidate keys, one of them will be selected as Primary Key and rest
of the column will serve as Alternate Key
➢ A Candidate Key which is not a primary key is an Alternate Key.
Foreign key
➢ Used to create relationship between two tables.
➢ It is a non-key attribute whose value is derived from the Primary key of another table.
➢ Foreign key column will for the value in Primary key of another table, if present then entry
will be allowed otherwise data will be rejected.
➢ Primary Key column table from where values will be derived is known as Primary Table
or Master Table or Parent Table and Foreign key column table will be Foreign Table or
Detail Table or Child table.
From the Above table definition, we can observe that the DEPTNO column of EMPLOYEE table
is deriving its value from DEPTNO of table DEPARTMENT. So we can say that the DEPTNO of
EMPLOYEE table is a foreign key whose value is dependent upon the Primary key column
DEPTNO of table DEPARTMENT.
REFERENTIAL INTEGRITY:
➢ Used to ensure relationship between records in related tables are valid and user don’t
accidentally delete or change the related data.
➢ Referential integrity can be applied when:
➢ The master table’s column is a Primary Key or has a unique index
➢ The related fields have the same data type
➢ Both tables must belong to same database.
➢ When referential integrity is enforced using Foreign Key you must observe the following
rules:
➢ You cannot enter a value in Child Table which is not available in Master Table’s Primary
key column. However you can enter NULL values in foreign key
➢ You cannot delete a record from Master Table if matching record exists in related table.
➢ You cannot modify or change the Primary Key value in Master table if its matching record
is present in related table.
STRUCTURED QUERY LANGUAGE
SQL – features
➢ Allows creating/modifying a database’s structure
➢ Changing security settings for system
➢ Permitting users for working on databases or tables
➢ Querying database
➢ Inserting/modifying/deleting the database contents
Classification of SQL
➢ DDL (Data Definition Language)
➢ DML (Data Manipulation Language)
➢ DCL (Data Control Language) or TCL (Transaction Control Language)
INTRODUCTION OF MYSQL
The Server
➢ Listens for client requests coming in over the network and access the database as per the
requirements and provide the requested information to the Client.
The Client
➢ Are the programs that connect to MySQL server and sends requests to the server and
receives the response of Server. Client may be the MySQL prompt or it may be Front-end
programming which connect to server programmatically like connecting to MySQL using
Python Language or Java or any other language.
FEATURES OF MYSQL:
➢ Speed - MySQL runs very fast.
➢ Ease of Use -Can be managed from command line or GUI
➢ Cost Is available free of cost. It is Open Source
➢ Query language Support -Supports SQL
➢ Portability – Can be run on any platform and supported by various compilers
➢ Data Types - supports various data types like Numbers, Char etc.
➢ Security -Offers privileges and password systems that is very flexible and secure.
➢ Scalability and Limits -Can handle large databases. Some of real life MySQL databases
contains millions of records.
➢ Connectivity-Clients can connect to MySQL using drivers
➢ Localization -The server can provide error message to client in many language
➢ Client and Tools -Provides several client and utility programs. Like mysqldump and
mysqladmin. GUI tools like MySQL Administration and Query Browser.
STARTING MYSQL:
Click on Start →All Programs →MySQL → MySQL Server→ MySQL →Command Line Client
To exit from MySQL type exit or quit in front of MySQL prompt.
MYSQL Elements
➢ Literals
➢ Data types
➢ Nulls
➢ Comments
Literals
➢ It means the fixed value or constant value. It may be of character, numeric or date time
type.
➢ Character and date/time literals are always in single quotation marks whereas numeric
literals must be without single quotation marks
➢ For example – ‘Virat’, 12, 12.56, ‘04-20-2018’
➢ Date and time values are always in the format YYYY-MM-DD HH:MI:SS
➢ Special character like quotes are always written be preceding it back-slash(\). For example
if we want to store value as Tom’s Cat then it should be written as Tom\’s Cat
Data Type
➢ Means the type of value and type of operation we can perform on data. For example on
numeric value we can store numbers and perform all arithmetic operations and so on.
➢ Numeric
➢ Date and time
➢ String types
➢ SHOW DATABASES- This command is used to list all databases on MySql Server
➢ USE <DATABASENAME>- This command is used to change/select/open given database
e.g. To open a database named ‘test’
>>> use test
➢ SHOW TABLES – This command will list all the tables from current database. If no database
is selected it will generate error.
➢ SELECT DATABASE () – This command will display the name of current database.
➢ DESC <TABLENAME> OR DESCRIBE <TABLENAME> - This command will be used
to display the structure of the table. For Eg: The above figure display the use of describe
command
➢ DROP TABLE <TABLENAME> - This command is used to permanently delete the table
from database.
For example, drop table pet; will delete pet table from database
➢ ALTER TABLE <TABLENAME> - This command is used to modify the structure of
existing table such as adding new column, removing existing column, rename or changing data
type, size and constraints.
o Adding new column to exiting table
Syntax :
➢ UPDATE <TABLENAME> - This command is used to update data from the table
Syntax:
UPDATE table_name SET column_name=new_value, column2_name=new_value
WHERE condition;
e.g. UPDATE emp set sal=sal+100 where ename =’Scot’
➢ INSERTING INTO TABLE_NAME – This command is used to add new row to the table
Syntax :
INSERT INTO table_name VALUES (list of values)
Syntax:
SELECT */ COLUMN LISTFROM TABLE(S)
WHERE CLAUSE/CONDITION
GROUP BY CLAUSE/COLUMN NAME
HAVING CLAUSE/CONDITION
ORDER BY COLUMN NAME ASC/DESC
Syntax:
ifnull(column, value_to_replace’)
Relational Operator
> greater than
< less than
>= greater than equal to
<= less than equal to
= equal
! = or <> not equal to
Logical Operator
And – evaluated true if all the logical expression is true otherwise false.
Or - evaluated true if any the logical expression is true otherwise false.
Logical operator is used to combine two or more logical expression,
Membership Operator
in –
Not in
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
➢ Comparing NULL
is null
is not null
NULL (Absence of value) value cannot be compared using Relational operator. The above
statement is used to check whether column contains NULL or not.
➢ Range Operator
Between
➢ Pattern Matching
Like
Not Like
Like clause is used to match pattern using two wild card characters
_ (underscore) – single unknown character
% (modulo) - Zero or more unknown characters
e.g.
words staring with ‘t’ ‘t%’
words ending with ‘t’ ‘%t’
words containing ‘t’ - ‘%t%’
word with ‘t’ as second letter - ‘_t%’
words with ‘t’ as third last character – ‘%t_ _’
words containing four letter and ‘t’ as second letter – ‘_ t_ _’
Syntax:
SELECT */col_list
FROM tablename
ORDER BY col1 asc/desc, col2 asc/desc;
AGGREGATE FUNCTIONS
➢ An aggregate function performs a calculation on multiple values and returns a single value.
➢ These function work on multiple rows collectively return single value.
➢ List of Aggregate functions are
o max() : return maximum value in set of value
o min() – return minimum value from the set of values
o avg() –return average value in set of non-null values
o sum() - Return the summation of all non-NULL values of the set of values.
o count() - Return the number of rows in a group
▪ Count(*) – return number of rows, including rows with NULL
▪ Count(column_name) - return number of rows, excluding rows with NULL
for the given column
➢ Group By Clause
o It is used in a SELECT statement to collect data across multiple records and group the
results by one or more columns.
Syntax:
SELECT column_name, aggregate_function
FROM table_name
GROUP BY column_name
In above example salary is grouped on job and maximum salary from each job is
displayed.
o Select clause involving group by clause can contain column present in group by clause,
aggregate function or no column. Otherwise it will return random data from other
column as given below.
➢ Having clause –
o Having clause is used to place condition on aggregate function in conjunction with
group by clause.
o Having clause in placed after where clause in select statement.
Syntax:
SELECT columm_name, aggregate_function(col_name)
FROM table
WHERE condition
GROUP BY column_name
HAVING aggregate_function(column_name) operator expression;
The above query will display deptno, maximum salary and number of employees from
each department.
The query given below display deptno, maximum salary and number of employees from
those department which have maximum salary greater than equal to 3000.
As condition is on aggregate function max(), where clause can’t be used in this case.
CREATE
i) Create the table HOSPITAL with datatypes and constraint as provided
COLUMN NAME DATA LENGTH CONSTRAINT
TYPE
NO Integer 5 PRIMARY KEY
NAME Character 20 NOT NULL
AGE Integer 3
DEPARTMENT Character 20 NOT NULL
DATEOFADM Date
CHARGES Float 7,2 Should not be less than zero
SEX Character 1 Default value if M
DOCTOR_ID Integer 4 References DOCTOR (D_ID)
ii) Create the table DOCTOR with datatypes and constraint as provided
COLUMN D_ID DOCTOR_NAME PHONE DATE_APPOINTMENT
NAME
DATATYPE Integer Character Character Date
LENGTH 3 20 10
CONSTRAINT PRIMARY NOT NULL UNIQUE
KEY
INSERT
i) Write the commands to insert the first two records in the table HOSPITAL
UPDATE
i) Change the Department of ZUBIN to RADIOLOGY
ii) Increase the Charges of Male patients by 5 %
iii) Input the age of ARUN as 26
DELETE
i) Delete the record of SHILPA
ii) Delete the record of all patients who under DOCTORID 104
ALTER
i) Add a new column Contact_Address char(30) to the table HOSPITAL
ii) Increase the column size of name by 10
iii) Add NOT NULL Constraint to Contact_Address column
DROP
i) Drop the table HOSPITAL
GROUP BY
i) Show the number of patients in each Department
ii) Show the average Charges paid by the patients in department ENT and CARDIOLOGY
iii) Show the min DATEOFADM of each Department where
minimum DATEOFADM isgreater than 22-Feb-1998
iv) SQL FUNCTIONS (STRING, MATHS and DATE/TIME)
➢ MATHS FUNCTIONS
Mathematical functions are also called number functions that accept numeric input and return
numeric values.
JOINS
➢ A relational database consists of multiple related tables linking together using common
columns, which are known as foreign key columns.
➢ It is used retrieve data from multiple tables.
➢ Consider the tables below EMP, DEPT & SALGARDE that stored related information, all
the examples on join will be explained with help of these following three tables
EMP Table
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 1993-06-13 800.00 0.00 20
7499 ALLEN SALESMAN 7698 1998-08-15 1600.00 300.00 30
7521 WARD SALESMAN 7698 1996-03-26 1250.00 500.00 30
7566 JONES MANAGER 7839 1995-10-31 2975.00 20
7698 BLAKE MANAGER 7839 1992-06-11 2850.00 30
7782 CLARK MANAGER 7839 1993-05-14 2450.00 10
7788 SCOTT ANALYST 7566 1996-03-05 3000.00 20
7839 KING PRESIDENT 1990-06-09 5000.00 0.00 10
7844 TURNER SALESMAN 7698 1995-06-04 1500.00 0.00 30
7876 ADAMS CLERK 7788 1999-06-04 1100.00 20
7900 JAMES CLERK 7698 2000-06-23 950.00 30
7934 MILLER CLERK 7782 2000-01-21 1300.00 10
7902 FORD ANALYST 7566 1997-12-05 3000.00 20
7654 MARTIN SALESMAN 7698 1998-12-05 1250.00 1400.00 30
DEPT TABLE
DEPTNO DNAME LOCATION
10 Accounting New York
20 Research Dallas
30 Sales Chicago
40 Operations Boston
SALGRADE TABLE
GRADE LOSAL HISAL
1 700.00 1200.00
2 1201.00 1400.00
4 2001.00 3000.00
5 3001.00 99999.00
3 1401.00 2000.00
➢ Types of Join
❖ Cartesian Product or Cross join
❖ Equi Join
❖ Natural Join
❖ Non-Equi Join
❖ Self Join
❖ Left Outer Join
❖ Right Outer Join
Syntax
SELECT * / Column_list
FROM Table1, Table 2
WHERE table1.column=Table2.column;
OR
SELECT * / Column_list
FROM Table1 join Table2 on Table1.Column=Table2.Column;
Example 1: Display the employee name, sal and name of department name
Ans: In the above query ename and sal belong to emp table whereas dname belongs to DEPT
table. So, to retrieve data in this we will use join
Note:
❖ In case of join full qualified (table_name.column_name) name is used to avoid
ambiguity as both table contains common columns as PRIMARY KEY and
FOREIGN KEY.
❖ Table Alias – Like column alias table alias can be used in case of join as given below.
SELECT e.ename, e.sal FROM emp e, dept d WHERE emp.deptno=dept.deptno;
➢ Here ‘e’ & ‘d’ are table alias for EMP & DEPT table respectively.Natural Join
❖ A natural join is a type of join operation that creates an implicit join by combining
tables based on columns with the same name and data type.
❖ It makes the SELECT query simpler with minimal use of conditions.
❖ There is no need to specify the name of common column in the SELECT statement.
❖ Common column is present only once in the output.
Syntax:
SELECT */column_list
FROM Table1 NATURAL JOIN TABLE2;
OR
SELECT * / column_list
FROM TABLE1 join on common_column_name;
Example :
SELECT * FROM emp JOIN dept USING(deptno);
OR
SELECT * FROM emp NATURAL JOIN DEPT;
Output:
Example
Consider the following tables – Bank_Account and Branch:
Table: Bank_Account
ACode Name Type
A01 Amrita Savings
A02 Parthodas Current
A03 Miraben Current
Table: Branch
ACode City
A01 Delhi
A02 Mumbai
A01 Nagpur