DATABASE
What is a Database?
• Database is a systematic collection of organized data or information
typically stored on a electronic media in a computer system. With
database data can be easily accessed, managed, updated, controlled
and organised.
• Many website on the world wide web widely use database system to
store and manage data (commonly referred as backend).
Advantages of Database
• Minimize Data Redundancy: In traditional File processing system same
piece of data may be held in multiple places resulting in Data redundancy
(duplicacy). Database system minimizes redundancy by data normalization.
• Increased Data consistency: When multiple copies of same data do not
match with one another is called as data inconsistency.
• Data Security: Database allows only the authorized user to access data in
the database.
• Data Sharing: Database allow its users to share data among themselves.
• Data Integrity: Data in the database accurate and consistent.
Data Model:
A data model is the way data is organised in a database. There are
different types data models controls the representation of data in a
database, these are:
•Relational Data model
•Network Data Model
•Hierarchical Data Model
•Object Oriented Data Model
The Relational data Model is far being used by most of the popular
Database Management Systems. In this course we limit our discussion
on Relational data model.
Relational Data Model
• In Relational data model data is organized into tables( rows and
columns). Tables in a relational model is called as Relations. Each row
of a relation represents a relationship between all the values in the
row.
Relational Database:
• A relational database is collection of multiple data sets organised as
tables. A relational database facilitates users to organize data in a well
defined relationship between database tables/relations. It uses
Structured Query Language(SQL) to communicate with the database
and efficiently maintain data in the database.
Relational Database:
Relational Database Terminologies
Attributes/Fields: Columns are referred as Attributes/Fields.
Cardinality: Total number of records in the relation is called as its
Cardinality.
Degree: Total number of Attributes/Fields in the relation is called as its
Degree.
Domain: permitted range of values of an attribute for an entity.
Primary key: The attribute or the set of attributes that uniquely
identifies records in a relation is called as the Primary key of the
Relation.
Types of Keys:
• Candidate Key: A Candidate key is a attribute/set of attributes that
uniquely identifies tuples in a relation. A relation may be more then
one candidate key.
• Primary Key: A Primary key is a attribute/set of attributes that uniquely
identifies tuples in a relation. All the values in the primary Key need to
be unique and NOT NULL.
• Among all the candidate keys the Database Administrator(DBA)
selects one as Primary key. A relation may have multiple Candidate
Keys but ONLY ONE Primary Key.
• Alternate Key: A alternate is basically is/are those candidate key which
is/are not used as Primary key of the relation.
• Foreign Key: Foreign key is a attribute of a relation(called as Child
table) that refere to the Primary Key of another relation(called as
parent table).
What is a Structured Query Language (SQL)?
• SQL is a standard language for storing, retrieving and manipulating
data on a relational database. All the relational database like MySql,
Oracle, MS Access, SQL server uses Structured query language(SQL)
for accessing and manipulating data.
• SQL provides wide range of effective command to perform all sort of
required operations on data such as create tables, insert record, view
recodes, update, alter, delete, drop, etc.
What is DDL and DML?
• All the SQL commands are categorized into five categories:
DDL,DML,DCL,DQL,TCL. In this course we are going to cover only DDL and
DML commands in detail.
• Data definition Language(DDL): Data Definition Language actually consists
of the SQL commands that can be used to define the database schema. It
simply deals with descriptions of the database schema and is used to
create and modify the structure of database objects in the database.
Example: Create, Drop, Alter, Truncate.
• Data Manipulation Language(DML): The SQL commands that deals with
the manipulation of data present in the database belong to DML or Data
Manipulation Language and this includes most of the SQL statements.
Example: Insert, Delete, Update.
Data Types in MySQL
• Data stored in a database table are of different types, As SQL developers we have chose
the suitable data types for each field while defining a table. SQL offers supports a wide
range of data types from which the developer can choose the most appropriate data
types for each column.
• char(size): used for fixed length string data.
• Example: A column defined as char(10) , it can contain string values of maximum 10
length. SQL allocates 10 bytes of memory irrespective of length of data to be stored.
• varchar(size): used for variable length string data.
• Example: If a column defined as varchar(10) , SQL allocates maximum 10 bytes to each
value, but bytes allocated may vary depending on the length of data.
• int( ): Used for integer/digits data without decimal. Can accommodate maximum 11
digit numbers.
• float(M,D): Permits real numbers up to M digits, out of which may be D digits after
decimal .
• Example: a column data type defined as float(6,3) may have 234.684
• Date: used to store date in YYYY-MM-DD format.
Constraints In SQL
• constraints are used to specify rules for the data in a table. Commonly used
constraints are:
• Not Null- Ensures that a column cannot have a NULL value
• Unique- Ensures that all values in a column are different
• Primary Key- A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
• Foreign Key- Prevents actions that would destroy links between tables
• Check – Ensures that the values in a column satisfies a specific condition
• Default- Sets a default value for a column if no value is specified
• MySql Commands
• CREATE Database: Used to create a new database.
• Syntax: CREATE DATABASE <database name>
• e.g. CREATE Database MySchool;
Database commands in SQL
• SHOW Databases: Used to list all existing databases.
• Syntax: SHOW Databases;
• DROP Database: Used to delete an existing database.
• Syntax: DROP Database <databasename>
• e.g. DROP Database MyStore;
• USE Database: Used to select/enter a existing database.
• e.g. USE MySchool;
Show Tables: After a database has been selected this command can be Used to list all the
tables in the database. e.g. SHOW TABLES;
CREATE Table:
Syntax: CREATE TABLE <table name>( column1 datatype,
column2 datatype,
……..
columnN datatype,
PRIMARY KEY( one or more columns ) );
E.g. CREATE TABLE cs_students(sid int(3), sname varchar(30), sclass int(2), smark int(3), skill
varchar(30), primary key(sid));
DESCRIBE Tables: A DDL command to display the structure of the table.
Syntax: DESCRIBE <table name>;
• ALTER Tables:
• ALTER TABLE is a DDL command that can change the structure of the table.
Using ALTER TABLE command we can add, delete or modify the
attributes/constraints of a table.
• Adding a column using Alter table:
• Syntax: ALTER TABLE <table name> ADD column <Column Name Data
type>;
• Deleting a column using Alter table:
• Syntax: ALTER TABLE <table name> DROP column <Column Name >;
Single Row Functions
The single row functions work with a single row at a time and return
one result per row. e.g.
String, Number, Date, Conversion and General function are single row
functions.
(i) String Functions
The string functions of MySQL can manipulate the text string in many
ways. String functions are broadly divided into two parts:
(a) Case-manipulation functions.
(b) Character-manipulation functions.
(a) Case-manipulation Functions
• These functions convert case for character strings:
SELECT
-> GRNUMBER,
-> SNAME,
-> UPPER(SNAME) AS SNAME_UPPER,
-> LOWER(SNAME) AS SNAME_LOWER
-> FROM student;
Database Commands in MySql
• To insert new rows into an existing table use the INSERT command:
mysql>INSERT INTO student values(‘dwivedi’,’freya’,’Udaipur’,’4’);
• We can insert record with specific column only
• mysql>INSERT INTO student(lastname,firstname,city)
values(‘dwivedi’,’Mohak’,’Udaipur’,);
• 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 mysql> SELECT * FROM
student;
• Database Commands in MySql 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; Selecting rows with null
values in specific column
• mysql> SELECT * FROM Student WHERE City IS NULL ;
• ❖ BETWEEN- to access data in specified range
• mysql> SELECT * FROM Student WHERE class between 4 and 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);
Pattern Matching
• SELECT * FROM Student WHERE Name LIKE ‘A%’;
• SELECT * FROM Student WHERE Name LIKE ‘A%’;
• SELECT * FROM Student WHERE Name LIKE ’%Singh%’;
• SELECT Name, City FROM Student WHERE Class>=8 AND Name LIKE
‘%Kumar%’ ;
• LIKE Operator A string pattern can be used in SQL using the following
wild card
• % Represents a substring in any length _ Represents a single
character
Order By clause
• MySQL Order By clause is used to sort the table data in either
Ascending order or Descending order. By default, data is not inserted
into Tables in any order unless we have an index.
• So, If we want to retrieve the data in any particular order, we have to
sort it by using MySQL Order By statement.
• Syntax:-
• SELECT Column_Names FROM Table_Name ORDER BY {Column1}[ASC
| DESC] {Column2}[ASC | DESC]
• select * from teacher order by ename asc;
Aggregate function
• An aggregate function performs a calculation on multiple values and returns a single
value. For example, you can use the AVG() aggregate function that takes multiple
numbers and returns the average value of the numbers.
• Following is the list of aggregate functions supported by mysql.
• Sum() – Adding /totaling value in respective filed
• Count() – Number of entries made in table
• Average()- finds Average value for the column
• max() – returns maximum value in the column
• Min() – returns minimum value in the column
• Select sum(salary) from teacher;
• Select count(*) from teacher;
• Select min(salary) from teacher;
• Select max(salary) from teacher;
CREATE TABLE USING CONSTRAINTS
• CREATE TABLE Persons ( ID int NOT NULL PRIMARY KEY, LastName
varchar(255) NOT NULL, FirstName varchar(255), Age int, City
varchar(255) DEFAULT ‘Jaipur', CONSTRAINT CHK_Person CHECK
(Age>=18) );
• CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT
NULL, PersonID int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID)
REFERENCES Persons(ID) );
Table with constraints
Creating Table with Constraints
• The following constraints are commonly used in SQL:
• NOT NULL -It Ensures that a column cannot have a NULL value
• UNIQUE - It Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
• FOREIGN KEY - It Uniquely identifies a row/record in another table
• CHECK - It Ensures that all values in a column satisfies a specific
condition
• DEFAULT - It Sets a default value for a column when no value is
specified
• INDEX - It is Used to create and retrieve data from the database very
quickly
Database Commands in MySql Altering Table
• The SQL ALTER TABLE command is used to add, delete or modify columns
in an existing table. You should also use the ALTER TABLE command to add
and drop various constraints on an existing table.
• The basic syntax of an ALTER TABLE command to add a New Column in an
existing table is as follows.
ALTER TABLE <table_name> ADD <column_name><datatype>;
The basic syntax of an ALTER TABLE command to DROP COLUMN in an
existing table is as follows.
ALTER TABLE <table_name >DROP COLUMN <column_name>;
The basic syntax of an ALTER TABLE command to change the DATA TYPE of a
column in a table is as follows.
ALTER TABLE <table_name> MODIFY COLUMN <column_name> <datatype>;