SlideShare a Scribd company logo
1 of 97
Download to read offline
Informatics Practices (IP)
Informatics Practices (IP)
Informatics Practices (IP)
By Arvind Sir
Unit 3 : Database Concepts and
SQL
Unit 3 : Database Concepts and
SQL
Unit 3 : Database Concepts and
SQL
“Database is an organized collection of related information stored
in easily accessible form which are integrated, shared and used
for multiple purposes”.
Database Technology is one of the most rapidly growing fields of Computer
Science. It is a computer based record keeping system, whose overall
purpose is to record and to maintain large volume of information that is
necessary for Organization management.
In this technology, the contents of database are obtained by combining data
from all the different sources, So that data are available to all Users to
access and manipulate database.
Database Concepts
Database Concepts
Advantages of Databases:
Data Redundancy is reduced
Data Inconsistency is controlled
Sharing of Data
Data Security
Data Integrity
Database Concepts
Database Concepts
A Database Management System is an integrated set of programs or
Software designed to store, modify, delete and extract information from
a database.
In other words, It is a collection of programs that enables users to create,
maintain and control all the access to database.
Some DBMS software are : FoxBASE, FoxPro, Sybase, MS-Access, ORACLE, MySQL etc.
DBMS offers the following services:
Data Definition: It is a method of defining data and storage.
Data Maintenance: It checks whether each record has field containing all
information for a particular record or not.
Data Manipulation: It allows data in the database to be inserted, updated,
deleted and stored.
Data Display: It helps in viewing data.
Data Integrity: It ensures the accuracy of the data.
Database Management System (DBMS)
Database Management System (DBMS)
DBMS involves four major components: Data, Hardware, Software and Users.
Data : The data stored in a system is partitioned into one or more database that
contains both the actual or operational data and the metadata. Generally, it is both
integrated and shared. DBMS exists to collect, store, process and access data.
Hardware: The hardware consists of a set of physical electronic devices such as
computers, I/O devices, storage devices(on which the database resides together with
the associated devices), etc. This provides the interface between computers and the
real world systems.
Software: This is the set of programs used to control and manage the overall
database. This includes the DBMS software itself, the Operating System, the network
software being used to share the data among users, and the application programs
used to access data in the DBMS.
Components of DBMS
Users : There are three broad categories of users: the Application Programmer, the
End-User and the Database Administrator(DBA).
Application Programmer : The Application Programmer is responsible for writing
Application programs that use the database. These application programs operate on
the data in all the usual ways i.e. Retrieving information, creating new information,
deleting or modifying existing information. All these functions are performed by
issuing the appropriate requests to the DBMS.
End-User : An End-User may employ a query language provided as integral part of the
system, or may invoke a user-written application program that accepts commands
from the terminal and the End-User may perform all the functions of retrieval, creation,
deletion and modification.
Database Administrator : DBA is to decide what information will be held in the
database to identify the information to be recorded about the entities.
Components of DBMS
Data model is an integrated collection of concepts that can be used for describing the
structure of the database and manipulating data, relationships between data and
constraints on the data in an organization.
That means, a database model shows the logical structure of a database, including
the relationships and constraints that determine how data can be stored and
accessed.
In fact, Data models define how data is connected to each other and how they are
processed and stored inside the system.
Different types of database models were introduced on the basis of the DBMS
implementations. These are referred to as :
1. Hierarchical Data Model
2. Network Data Model
3. Relational Data Model
Database Models
1. Hierarchical Data Model : The hierarchical model was one of the earliest data model. This
model organizes data into a tree-like structure, where each record has a single parent or
root and can be used to construct a hierarchy of records in the form of nodes and
branches.
In the above example the root record represents some product i.e. shoes which is composed of
part Women’s shoes and Men’s shoes, each of these are composed of subparts like High
Heels, Bellies, sports shoes, Sneakers etc.
This model does not support many-to-many relationship because the links in hierarchical model
are unidirectional i.e. we can travel parent to the child only. So if we need any information from
lower level then we have to follow complete hierarchy of the system.
Database Models
2. Network Data Model : The Network data model can be equated with a network file
structure which supports all relationship restricted to be either binary or many-
one relationships. In this structure it is possible for one node to share ownership
of a model at a lower level with another node in a separate branch of a tree.
In Network model, the data is represented by collections of records and relationships
among data are represented as links.
Database Models
3. Relational Data Model : The Relational model is developed by (IBM’s) Dr. E. F. Codd in 1969. This
model is based on the concept that data is organized and stored in two-dimensional tables called
relations.
A Relational model consists of a collection of tables, each of which is assigned a unique name, i.e. it
represents the database as a collection of relations or tables with rows (record) and columns
(fields). The rows of a relation are called Tuples (pronounced to rhyme with “Couple”) and the
columns of a relation are called Attributes.
Relational data model is the data model, which is used widely around the world for data storage and
processing. This model is simple and it has all the properties and capabilities required to process
data with storage efficiency.
Database Models
The Relational data model eliminated all parent-child relationships and instead represented
all data in the database as simple row/column tables of data values.
A relation is similar to a table with rows / columns of data values. The rows of a table are
referred to as Tuples and the columns are referred to as Attributes. Several tuples of equal
length placed one below the other create a table.
Each table is am independent entity and there is no physical relationship between a table.
Relational model of data management is based on set theory. Built-in query language is
designed in the RDBMS, so that it can manipulate set of data (one or more tuples)
The user interface used with relational models in non-procedural, because only what needs
to be done is specified and not how it has to be done.
Characteristics of a Relational DBMS Model
The components used in Relational model are outlined as follows:
Entities
Attributes
Relationships
Entities: Entities are the fundamental building blocks of Relational Database
design. An entity defines any person, place, thing or concept for which data will be
collected. For example :
Components of a Relational Model
Person Student, Teacher
Place Classroom
Thing Computer (Lab equipment)
Concept Study
Attributes : Attributes are additional characteristics or information for an entity.
An attribute describes a property associated with entities. It will have a name and
a value for each entity. For example, Rollno, Name, Address, Pincode, etc.
These attributes can be defined for a student. A specific student will have value for
each of these attributes.
Relationships : A Relationship is a logical linkage between two entities that
describes how the entities are associated with each other.
For example:
One- to–one relationship
One-to-many or Many-to-one relationship
Many-to-many relationship
Components of a Relational Model
Objects Description
Relation (Table) A relation is a table with rows and columns.
Tuple (Row, Record) A tuple is a row in a relation.
Attribute (Column, Field) Attribute is the named column of a relation.
Domain (set of legal values) A domain is the set of allowable values for
one or more attributes.
Degree (Number of columns) The degree of a relation is the number of
attributes it contains.
Cardinality (Number of rows) The cardinality of a relation is the number of
tuples it contains.
RDBMS Terminology
A key allows us to identify a set of attributes that distinguishes entities from each
other.
Primary Key
Foreign Key
Candidate Key
Alternate Key
Primary Key: A Primary Key is a set of one or more attributes or columns that are
uniquely identify tuples within the relation. The Primary key values should never be
changed and should never be null. For example, Stud_ID, RollNo, AdmNo etc.
Foreign Key : A Foreign key is a column or group of columns whose values are
derived from the Primary key of another table. It represents relationships between two
or more tables.
When relationship is created between two or more tables, the Master table
contributes its Primary key to the Transaction table which is known as Foreign key.
Keys in MySQL
Candidate Key: All attributes inside a relation that can serve as Primary key are
Candidate key as they are candidates for Primary key.
Following are the important differences between Primary Key and Candidate key
Keys in MySQL
Sr. No. Key Primary Key Candidate key
1
Definition Primary Key is a unique and non-null key which
identify a record uniquely in table. A table can have
only one primary key.
Candidate key is also a unique key to identify a
record uniquely in a table but a table can have
multiple candidate keys.
2
Null Primary key column value can not be null. Candidate key column can have null value.
3
Objective Primary key is most important part of any relation
or table.
Candidate key signifies as which key can be used
as Primary Key.
4
Use Primary Key is a candidate key. Candidate key may or may not be a primary key.
AlternateKey: A candidate key not selected as a primary key is called alternate or
secondary key. That means, any attribute that is the candidate for the primary key but
is not Primary key is called Alternate key.
Let us see an example −
Above, Student_ID, Student_Enroll and Student_Email are the candidate keys. They are considered candidate keys
since they can uniquely identify the student record. Select any one of the candidate key as the primary. Rest of the
two keys would be Alternate or Secondary Key.
Let’s say you selected Student_ID as primary key, therefore Student_Enroll and Student_Email will be Alternate Key
(candidates of primary key).
Keys in MySQL
Student_ID Student_Enroll Student_Name Student_Email
096 2717 Manish aaa@gmail.com
055 2655 Manan abc@gmail.com
067 2699 Shreyas pqr@gmail.com
MySQL stands for “My Structured Query Language”.
MySQL is an open source and freely available Relational Database
Management System (RDBMS) that uses Structured Query
Language (SQL). It provides excellent features for creating,
storing, maintaining and accessing data stored in the form of
Databases and their respective tables.
MySQL was developed by the company MYSQL AB founded in Sweden. At
first, MySQL was not intended to be a commercial product. Sun Micro
Systems aquired MYSQL AB in 2008, which holds the copyright. It is fully
secured reliable and possesses better functionalities than many other
commercial RDBMS.
Inventer: Michael Widenius “Monty”, David Axmark & Allan Larson
Overview of MySQL
Overview of MySQL
Cost : MySQL is open source and is available free of cost.
Performance : MySQL is very fast, because it supports clustered
servers for demanding applications.
Easy to use : MySQL is high performance relatively simple database
system.
Simplicity : MySQL is easy to install.
Data Security : MySQL has powerful mechanisms for ensuring only
authorized users have access, support for safe and secure connections,
powerful data encryptions & decryption functions.
Application Support : MySQL has an API for just about any
programming language. Specifically, we can write database applications
that access MySQL in C, C++, Java etc.
Features of MySQL
Features of MySQL
SQL ( pronounced “ess – que – el” or “sequel” ) stands for Structured
Query Language.
SQL is the most common standard language for accessing and
manipulating databases. It is fourth generation non – procedural
language that is used to create, manipulate and process the databases.
SQL was originated by Donald D. Chamberlin and Raymond F. Boyce in
1974 at IBM’s Son Jose Research Centre and standardized by ANSI
(American National Standards Institutes) and ISO (International
Standard Organization) in 1986. SQL has emerged as Standard
Language for relational DBMS and most commercial Relational
Database Management System use SQL.
The key features of SQL are:
Non – procedural Language
Unified Language
Common language for all Relational Databases
Introduction to SQL
Introduction to SQL
SQL (Structured Query Language) is made of four sub languages as
follows :
Data Definition Language (DDL)
Data Manipulation Language (DML)
Transaction Control Language (TCL)
Classification of SQL Commands
Creating Database - CREATE DATABASE
Viewing a List of Databases - SHOW DATABASES
Accessing Database – USE
Viewing a List of Tables - SHOW TABLES
Creating Table – CREATE TABLE
Viewing a Table Structure - DESCRIBE
Inserting Data into Table – INSERT INTO
Making Simple Queries – SELECT
Modifying Data in Tables – UPDATE
Deleting Data from Tables – DELETE
Altering Tables – ALTER TABLE
Dropping Tables – DROP TABLE
SQL Commands
SQL Commands
Syntax : CREATE DATABASE <Database Name>;
Example :
Mysql> CREATE DATABASE Employee ;
Database created
Mysql> SHOW DATABASES ;
Creating Database - CREATE DATABASE
Creating Database - CREATE DATABASE
Creating Database - CREATE DATABASE
Syntax : USE <Database Name>;
Example :
Mysql> USE Employee ;
Database changed
Mysql> SHOW TABLES ;
Accessing Database – USE
Accessing Database – USE
Accessing Database – USE
Syntax : CREATE TABLE <Table_name >
(
Column1 Datatype(Size),
Column2 Datatype(Size),
Column3 Datatype(Size)
);
Example: Create a table Emp with the following structure
Creating Tables – CREATE TABLE
Creating Tables – CREATE TABLE
Creating Tables – CREATE TABLE
Column Name Data Type Size
Ecode INT 4
Ename VARCHAR 30
Dept VARCHAR 12
City VARCHAR 15
Gender CHAR 1
Salary FLOAT 7,2
Mysql> CREATE TABLE Emp
(
Ecode INT(4),
Ename VARCHAR(30),
Dept VARCHAR(12),
City VARCHAR(15),
Gender CHAR(1),
Salary FLOAT(7,2)
);
Creating Tables – CREATE TABLE
Creating Tables – CREATE TABLE
Creating Tables – CREATE TABLE
Column Name Data Type Size
Ecode INT 4
Ename VARCHAR 30
Dept VARCHAR 12
City VARCHAR 15
Gender CHAR 1
Salary FLOAT 7,2
“Constraints are rules that can be used to control the invalid data entry in a
column.” Constraints are a part of the table definition that limit the values
entered into its column.
Some common types of Constraints are :
NOT NULL
UNIQUE
PRIMARY KEY
DEFAULT
CHECK
FOREIGN KEY
SQL Constraints
SQL Constraints
1. NOT NULL Constraint:
The NOT NULL Constraints ensure that the user always type the value for that
column i. e. the column becomes a mandatory column. That means NOT NULL
specifies that a column must have some value.
Example : Gender CHAR(1) NOT NULL;
2. UNIQUE Constraint:
The UNIQUE Constraints ensure that the value for that column is unique or distinct.
That means the value entered in UNIQUE column must not be repeated across the
column.
Note: UNIQUE key can be NULL at the time of data entry, So value is not mandatory
for UNIQUE column.
Example : Ecode INT(4) UNIQUE;
SQL Constraints
SQL Constraints
3. PRIMARY KEY Constraint:
The PRIMARY KEY Constraints specifies that the column(s) in the table are prime
key and must have unique value across the column and column can’t be le left
blank.
Example : Ecode INT(4) PRIMARY KEY;
4. DEFAULT Constraint:
The DEFAULT Constraints specifies a default value to the column if no value
entered by the user. Default value can be assigned to a column at the time of
table creation.
Example : City VARCHAR(15) DEFAULT = ‘Patna’;
SQL Constraints
SQL Constraints
5. CHECK Constraint:
The CHECK Constraints ensure that when data is entered, the data in the column is
limited to specific value that satisfy certain criteria or condition.
Example : Category VARCHAR(4) CHECK Category IN(‘SC’, ‘ST’, ‘OBC’,’GEN);
6. FOREIGN KEY Constraint:
The FOREIGN KEY Constraint is used to represent relationship between two or
more tables. The FOREIGN KEY is defined in the child table containing the
referenced column
Example : FOREIGN KEY(Ecode) REFERENCES Emp(Ecode);
SQL Constraints
SQL Constraints
Syntax : CREATE TABLE <Table_name >
(
Column1 Datatype(Size) [Constraint],
Column2 Datatype(Size) [Constraint],
Column3 Datatype(Size) [Constraint]
);
Example: Create a table Emp with the following structure
Creating Tables with SQL Constraints – CREATE TABLE
Creating Tables with SQL Constraints – CREATE TABLE
Creating Tables with SQL Constraints – CREATE TABLE
Creating Tables with SQL Constraints – CREATE TABLE
Column Name Data Type Size Constraints
Ecode INT 4 PRIMARY KEY
Ename VARCHAR 30
Dept VARCHAR 12
City VARCHAR 15
Gender CHAR 1 NOT NULL
Salary FLOAT 7,2
Column Name Data Type Size Constraints
Ecode INT 4 PRIMARY KEY
Ename VARCHAR 30
Dept VARCHAR 12
City VARCHAR 15
Gender CHAR 1 NOT NULL
Salary FLOAT 7,2
Mysql> CREATE TABLE Emp
(
Ecode INT(4) PRIMARY KEY,
Ename VARCHAR(30),
Dept VARCHAR(12),
City VARCHAR(15),
Gender CHAR(1) NOT NULL,
Salary FLOAT(7,2)
);
Creating Tables with SQLConstraints – CREATE TABLE
Creating Tables with SQLConstraints – CREATE TABLE
Creating Tables with SQLConstraints – CREATE TABLE
Creating Tables with SQLConstraints – CREATE TABLE
Column
Name
Data Type Size Constraints
Ecode INT 4 PRIMARY KEY
Ename VARCHAR 30
Dept VARCHAR 12
City VARCHAR 15
Gender CHAR 1 NOT NULL
Salary FLOAT 7,2
This command is used to display the structure of the table. ( i. e. this command
display column names and data types as well as whether a column must contain
data).
Syntax : DESC / DESCRIBE <Table Name>;
Example :
Mysql> DESC Emp; OR Mysql> DESCRIBE Emp;
Displaying Table Structure – DESCRIBE or DESC
Displaying Table Structure – DESCRIBE or DESC
Displaying Table Structure – DESCRIBE or DESC
This command is used to insert the data into the table.
Insert operation:
Creates a new row in the table.
Stores the values passed into the column field.
Note: using the INSERT command only one row is inserted at a time.
Syntax : INSERT INTO <Table Name> [ <Column List> ]
VALUES ( value 1, value 2, ………….. ) ;
Example 1:
Mysql> INSERT INTO Emp
VALUES(1001, “A. Williams”, “Production”, “Ahmedabad”, “M”,46000);
Inserting Data into Table – INSERT INTO
Inserting Data into Table – INSERT INTO
Inserting Data into Table – INSERT INTO
Example 2: To insert data only in specific columns i. e. Ecode, Ename and Gender columns.
Mysql> INSERT INTO Emp (Ecode, Ename, Gender)
VALUES(1002, “Kuldip”, “M”);
OR
Mysql> INSERT INTO Emp
VALUES(1002, “Kuldip”, NULL, NULL,“M”, NULL);
Inserting Data into Table – INSERT INTO
Inserting Data into Table – INSERT INTO
Inserting Data into Table – INSERT INTO
Insert the following Data into the Table – Emp
Insert the following Data into the Table – Emp
Insert the following Data into the Table – Emp
Insert the following Data into the Table – Emp
Ecode Ename Dept City Gender Salary
1001 A. Williams Production Ahmedabad M 46000
1002 Sanjeev Batra Personnel Jalandhar M 30000
1003 Ishita Sharma RND New Delhi F 50000
1004 Suresh Baroth RND Jaipur M 55000
1005 Seema Sharma Marketing Shimla F 36500
1006 Akram Hussain Servicing Hamirpur M 20000
1007 Dhiraj Patel Production Surat M 45000
1008 Meera Kumari RND Phagwara F 40000
A SELECT command retrieves information from the table.
Using a SELECT command, we can do the following:
Selection : The selection capability in SQL can use to choose the rows in a table
that we want returned by a query. We can use criteria or condition to selectively
restrict the rows that we see.
Projection : The projection capability in SQL can use to choose the columns in a
table that we want returned by a query. We can choose as many columns of the
table as we require.
Join : The join capability in SQL can use to bring together data stored in different
tables by creating a link between them.
Displaying Information from the Table - SELECT
Displaying Information from the Table - SELECT
Displaying Information from the Table - SELECT
Syntax : SELECT [ DISTINCT <Column Name> ] { * | <Column List> [Alias] }
FROM <Table Name> ;
[ WHERE <Condition> ]
[ ORDER BY <Column Name> ASC | DESC ]
Making Simple Queries – SELECT
Making Simple Queries – SELECT
Making Simple Queries – SELECT
In the Syntax :
SELECT is a list of one or more columns
DISTINCT eliminates duplicates across the given column
* Selects all columns
Column List selects the specified column
Alias gives selected columns different Headings
Uses: <Old column name> AS < New column name >
FROM <Table> specifies the table containing the columns
Consider the following Data into the Table – Emp
Consider the following Data into the Table – Emp
Consider the following Data into the Table – Emp
Consider the following Data into the Table – Emp
Ecode Ename Dept City Gender Salary
1001 A. Williams Production Ahmedabad M 46000
1002 Sanjeev Batra Personnel Jalandhar M 30000
1003 Ishita Sharma RND New Delhi F 50000
1004 Suresh Baroth RND Jaipur M 55000
1005 Seema Sharma Marketing Shimla F 36500
1006 Akram Hussain Servicing Hamirpur M 20000
1007 Dhiraj Patel Production Surat M 45000
1008 Meera Kumari RND Phagwara F 40000
1. Selecting All Columns :
Syntax: SELECT * FROM <Tablename>;
Example:
Mysql> SELECT * FROM Emp;
The output of this command would be to display the whole table because * has
selected all columns.
2. Selecting Specific Columns :
Syntax: SELECT < List of columns>
FROM <Tablename>;
Example:
Mysql> SELECT Ecode, Ename, Salary FROM Emp;
The output of this command would be to display the information of three
columns (i. e. Ecode, Ename and Salary) of table Emp.
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
4.
3. Eliminating Duplicate Data (DISTINCT Keyboard):
Syntax: SELECT DISTINCT <Column Name> FROM <Tablename>;
Example:
Mysql> SELECT DISTINCT Dept FROM Emp;
Using Arithmetic Operators:
Example 1:
Mysql> SELECT Ecode, Ename, Salary + 500 FROM Emp;
Example 2:
Mysql> SELECT 2 + 5;
Output: 7
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Working with Emp Table using SELECT command
Syntax : SELECT [ DISTINCT <Column Name> ] { * | <Column List> [Alias] }
FROM <Table Name>
WHERE <Condition> ;
The WHERE Clause with SELECT Command
The WHERE Clause with SELECT Command
The WHERE Clause with SELECT Command
The WHERE Clause with SELECT Command
The WHERE Clause with SELECT Command
In the Syntax :
WHERE restricts the query to rows that meet a condition
<Condition> is composed of column names, expressions, constants and a
comparison or relational operator.
* The WHERE clause consists of three elements : 1. Column Name 2.
Comparison operator 3.Constant or list of values
The WHERE clause is used along with the SELECT command to specify the
condition or criteria , based on which row will be extracted from the table.
Note : WHERE clause examines each row to determine if the condition is true
with respect to the row.
Q. 1. Display the Name and Department of those Employees where department is
Production.
Sol.: SELECT Ename, Dept
FROM Emp
WHERE Dept = “Production” ;
Q. 2. Display the Name and Salary of those Employees whose salary is more than 40,
000.
Sol.: SELECT Ename, Salary
FROM Emp
WHERE Salary > 40000 ;
Q. 2. Display the Name of female Employees in the table.
Sol.: SELECT Ename
FROM Emp
WHERE Gender = ‘F’;
Working with Emp Table using WHERE clause
Working with Emp Table using WHERE clause
Working with Emp Table using WHERE clause
Working with Emp Table using WHERE clause
Working with Emp Table using WHERE clause
Working with Emp Table using WHERE clause
Working with Emp Table using WHERE clause
Q. 4. Display the Name and Department of Employees working in Production and
servicing Department.
Sol.: SELECT Ename, Dept
FROM Emp
WHERE Dept = “Production” OR Dept = “Servicing” ;
Q. 5. Display the Ecode, City and Salary of those Employees who are living in
Jalandhar and have salary greater than 20,000.
Sol.: SELECT Ename, City, Salary
FROM Emp
WHERE City = ‘Jalandhar’ AND Salary > 20000 ;
Q. 6. Display the Name of Employees who are not females.
Sol.: SELECT Ename
FROM Emp
WHERE Gender != ‘F’;
The WHERE clause with Logical Operators
The WHERE clause with Logical Operators
The WHERE clause with Logical Operators
The WHERE clause with Logical Operators
The WHERE clause with Logical Operators
The WHERE clause with Logical Operators
Q. 7. Display the details of Employees, whose Salary is between 40,000 and 50,000.
Sol.: SELECT *
FROM Emp
WHERE Salary BETWEEN 40000 AND 50000;
Q. 8. Display the code, names of the Employees having Ecode 1001, 1004 and 1008.
Sol.: SELECT Ecode, Ename
FROM Emp
WHERE Ecode IN(1001, 1004, 1008);
Q. 9. Display the Name of Employees who live in city Jalandhar, New Delhi or
Ahmedabad.
Sol.: SELECT Ename
FROM Emp
WHERE City IN (‘Jalandhar’, ‘New Delhi’, ‘Ahmedabad’);
The WHERE clause with Special Operators
The WHERE clause with Special Operators
The WHERE clause with Special Operators
The WHERE clause with Special Operators
The WHERE clause with Special Operators
The WHERE clause with Special Operators
LIKE Operator :
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column. It determines if a character string matches a specified pattern (i. e.
regular character and wildcard characters) to filter row based on pattern matching.
In other words LIKE operator is used to perform wildcard ( match a character
pattern ) searches of String values.
There are two wildcard symbols used in conjunction with LIKE operator:
The WHERE clause with Special Operators
The WHERE clause with Special Operators
The WHERE clause with Special Operators
The WHERE clause with Special Operators
The WHERE clause with Special Operators
The WHERE clause with Special Operators
Symbol Description
% (Percent) Represents any sequence of zero or more characters.
_ (Underscore) Represents any single character.
Q. 1. Display the Name of Employees, whose Names start with “S”.
Sol.: SELECT Ename
FROM Emp
WHERE Ename LIKE “S%”;
Q. 2. Display the Ecode and Name of Employees, whose Names ending with “a”.
Sol.: SELECT Ecode, Ename
FROM Emp
WHERE Ename LIKE ‘%a’;
Q. 3. Display the Name of Employees whose Names having ‘e’ as the third character.
Sol.: SELECT Ename
FROM Emp
WHERE Ename LIKE “_ _e%”;
The WHERE clause with LIKE Operators
The WHERE clause with LIKE Operators
The WHERE clause with LIKE Operators
The WHERE clause with LIKE Operators
The WHERE clause with LIKE Operators
The WHERE clause with LIKE Operators
IS NULL Operator :
The IS NULL operator tests for values that are NULL. NULL value is different from
assigning a column with the value 0 or a blank. It cannot be compared using the
relational and logical operator.
A NULL value means value is unavailable unknown or inapplicable.
The WHERE clause with IS NULL Operators
The WHERE clause with IS NULL Operators
The WHERE clause with IS NULL Operators
The WHERE clause with IS NULL Operators
The WHERE clause with IS NULL Operators
The WHERE clause with IS NULL Operators
Q. 3. Display the Name of Employees not assigned to any department.
Sol.: SELECT Ename
FROM Emp
WHERE Dept IS NULL;
ORDER BY clause:
The ORDER BY clause can be used with SELECT command to sort or arrange the
rows according to the values in one or more selected column in Ascending or
Descending order .
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
Syntax :
SELECT [ DISTINCT <Column Name> ] { * | <Column List> [Alias] }
FROM <Table Name>
[ WHERE <Condition> ]
[ ORDER BY <Column Name> ASC | DESC ] ;
In the syntax:
ORDER BY Specifies the order in which the retrieved rows are displayed.
ASC Sorts the rows in ascending order. (By default)
DESC Sorts the rows in descending order.
Q. 1. Display Employees code, name and salary in ascending order of salary.
Sol.: SELECT Ecode , Ename , Salary
FROM Emp
ORDER BY Salary;
Q. 2. Display Employees code, name and salary in descending order of salary.
Sol.: SELECT Ecode, Ename
FROM Emp
ORDER BY Salary DESC;
Q. 3. Display Employees name and salary in descending order of salary, whose salary
is more than 40000.
Sol.: SELECT Ename , Salary
FROM Emp
WHERE Salary > 40000
ORDER BY Salary DESC;
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
The ORDER BY clause with SELECT Command
The UPDATE command modifies the values of one or more columns in
selected rows of a table.
Syntax :
UPDATE <Table Name>
SET <Column Name> = <value>
[ WHERE <Condition> ] ;
Modifying Data in Tables – UPDATE Command
Modifying Data in Tables – UPDATE Command
Modifying Data in Tables – UPDATE Command
In the syntax:
UPDATE Change the values on all table rows that satisfy condition.
SET Specifies which column are to be updated with given value.
WHERE Selects the rows of the table to be modified.
NOTE : UPDATE sets each column name equal to the corresponding value
in the row selected by the condition.
Q. 1. Increase every Employees salary by 10%.
Sol.: UPDATE Emp
SET Salary = Salary + Salary * 0.1;
Q. 2. Change the department of Ishita Sharma to Servicing
Sol.: UPDATE Emp
SET Dept = ‘Servicing’
WHERE Ename = ‘Ishita Sharma’;
Modifying Data in Tables – UPDATE Command
Modifying Data in Tables – UPDATE Command
Modifying Data in Tables – UPDATE Command
Modifying Data in Tables – UPDATE Command
The DELETE command removes existing rows from a table.
Syntax :
DELETE
FROM <Table Name>
[ WHERE <Condition> ] ;
Deleting rows from Tables – DELETE Command
Deleting rows from Tables – DELETE Command
Deleting rows from Tables – DELETE Command
NOTE : DELETE command removes only rows from the table but cannot
removes columns..
Q. 1. Delete all the records of RND Department.
Sol.: DELETE
FROM Emp
WHERE Dept = ‘RND’;
Q. 2. Delete all the records of Employees having Salary less than 40000.
Sol.: DELETE
FROM Emp
WHERE Salary < 40000;
Q. 3. Delete all records from the table.
Sol.: DELETE
FROM Emp;
Deleting rows from Tables – DELETE Command
Deleting rows from Tables – DELETE Command
Deleting rows from Tables – DELETE Command
The ALTER TABLE command is used to modify or to change the
structure of the existing table.
Tables can be altered in one of the three ways:
By adding a new column
By changing a column’s definition
By dropping a column
Altering Tables – ALTER TABLE
Altering Tables – ALTER TABLE
Altering Tables – ALTER TABLE
We can add a new column to a table by using ALTER TABLE command
with the ADD clause.
Syntax :
ALTER TABLE <Table Name>
ADD <Column Name Datatype(size)>;
Adding a new column in a table
Adding a new column in a table
Q. Add a column to the existing table EMP which will hold the Grades for each
Employee.
Sol.: ALTER TABLE Emp
ADD Grade VARCHAR(6);
* The new column becomes the last column.
* Verify the adding by using DESCRIBE or DESC Command.
We can modify a column definition by using ALTER TABLE command
with the MODIFY clause. Column modification can include changes to
a column’s Datatype and Size.
Syntax :
ALTER TABLE <Table Name>
MODIFY (<Column Name Datatype(size)>);
Modifying a column in a table
Modifying a column in a table
Q. Modify the Salary column with DECIMAL datatype having Size 10.
Sol.: ALTER TABLE Emp
MODIFY (Salary DECIMAL(10));
* Verify the result of using DESCRIBE or DESC Command.
1.
2.
We can drop or remove a column from a table by using ALTER TABLE
command with the DROP COLUMN clause.
The column may or may not contain data.
Only one column can be dropped at a time.
Syntax :
ALTER TABLE <Table Name>
DROP COLUMN <Column Name >;
Dropping a column in a table
Dropping a column in a table
Q. Remove the Grade column from the table.
Sol.: ALTER TABLE Emp
DROP COLUMN Grade;
* The Grade column will be deleted.
We can change a column heading to a table by using ALTER TABLE
command with the CHANGE clause.
Syntax :
ALTER TABLE <Table Name>
CHANGE <Old Column Name > <New Column Name Definition >;
Changing a column heading in a table
Changing a column heading in a table
Q. Change the name of column Dept as Department.
Sol.: ALTER TABLE Emp
CHANGE Dept Department VARCHAR(15);
The DROP TABLE command is used to remove the entire table along
with its structure permanently from the Database.
Dropping Table – DROP TABLE
Dropping Table – DROP TABLE
Dropping Table – DROP TABLE
Syntax :
DROP TABLE <Table Name> ;
Q. Remove the table EMP along with its structure.
Sol.: DROP TABLE Emp;
Unit 2 : Database Query
Unit 2 : Database Query
using SQL
using SQL
Functions in MySQL
1.
“A function is a set of predefined commands that performs specific
operation and returns value(s). “
MySQL functions may accept argument and always return a value.
The functions used in SQL can be categorised into two categories:
1. Single Row Functions or Scalar Functions
2. Multi Row Functions or Aggregate functions
Single Row Functions: The single Row Functions work with a single
row at a time and return one result per row.
Example:
String Functions
Mathematical of Numeric Functions
Date and Time Functions
Functions in MySQL
Functions in MySQL
Table – Emp
Table – Emp
Table – Emp
Table – Emp
Table – Emp
Ecode Ename Dept City Gender Salary
1001 A. Williams Production Ahmedabad M 46000
1002 Sanjeev Batra Personnel Jalandhar M 30000
1003 Ishita Sharma RND New Delhi F 50000
1004 Suresh Baroth RND Jaipur M 55000
1005 Seema Sharma Marketing Shimla F 36500
1006 Akram Hussain Servicing Hamirpur M 20000
1007 Dhiraj Patel Production Surat M 45000
1008 Meera Kumari RND Phagwara F 40000
String functions are being used to manipulate the text string. Some of
the commonly used string function of MySQL are as follows:
1. LENGTH() : Length() function returns the length of a string i.e. Number of
characters in a string including letters, spaces and anything else.
Syntax :
LENGTH( String | Column)
String or Text Functions
String or Text Functions
Example:
SELECT LENGTH(“Informatics Practices”);
Output: 21
Q. Display the Employee Name and their length from Emp table.
Sol.: SELECT Ename , LENGTH(Ename)
FROM Emp;
.
2. UCASE() / UPPER() : Ucase() / Upper() takes any String or Column name and
converts any letters in it to Capital letters or uppercase.
Syntax :
UCASE / UPPER( String | Column name)
String or Text Functions
String or Text Functions
Example:
SELECT UCASE(“Informatics Practices”); OR
SELECT UPPER(“Informatics Practices”);
Output: INFORMATICS PRACTICES
Q. Display all city names to upper case in Emp table.
Sol.: SELECT UPPER(City)
FROM Emp;
.
3. LCASE() / LOWER() : Lcase() / Lower() takes any String or Column name and
converts any letters in it to Small letters or lowercase.
Syntax :
LCASE / LOWER( String | Column name)
String or Text Functions
String or Text Functions
Example:
SELECT LCASE(“Informatics Practices”); OR
SELECT LOWER(“Informatics Practices”);
Output: informatics practices
Q. Display all city names to lower case in Emp table.
Sol.: SELECT LOWER(City)
FROM Emp;
*LOWER() does opposite to UPPER function
4. LEFT( ) : LEFT( ) function returns the number of characters as specified from
leftmost side of the String or Column name.
Syntax :
LEFT( String | Column name , length)
* Where length is the number of characters to be returned.
String or Text Functions
String or Text Functions
Example:
SELECT LEFT(“Informatics Practices” , 6);
Output: Inform
Q. Display left five characters from Ename column of the Emp table.
Sol.: SELECT LEFT(Ename , 5)
FROM Emp;
5. RIGHT( ) : RIGHT( ) function returns the number of characters as specified from
rightmost side of the String or Column name.
Syntax :
RIGHT( String | Column name , length)
* Where length is the number of characters to be returned.
String or Text Functions
String or Text Functions
Example:
SELECT RIGHT(“Informatics Practices” , 3);
Output: ces
Q. Display last three characters from Ename column of the Emp table.
Sol.: SELECT RIGHT(Ename , 3)
FROM Emp;
6. SUBSTR( ) / SUBSTRING() : This function returns a specified characters from
string starting at character position m to n characters long.
Syntax :
SUBSTR | SUBSTRING( String | Column name , m , n)
* Where m is the starting character position and n is the number of characters.
String or Text Functions
String or Text Functions
Example:
SELECT SUBSTR(“Informatics Practices” , 3 , 4);
Output: form
SELECT SUBSTR(“INFORMATION” , -6 , 3);
Output: MAT
Q. Display the City starting at second character and four characters.
Sol.: SELECT SUBSTR(City , 2 , 4)
FROM Emp;
7. MID( ) : MID( ) function returns a substring starting from the specified position
to the specified number of characters from String or Column name.
Syntax :
MID( String | Column name , Start_Position , length)
* Where length is the number of characters to be returned.
String or Text Functions
String or Text Functions
Example:
SELECT MID(“Informatics Practices” , 3 , 4);
Output: form
Q. Display first three characters extracted from Ename of Employees.
Sol.: SELECT MID(Ename , 1 , 3)
FROM Emp;
8. INSTR( ) : This function searches String1 for String2 and returns the position of
the first occurrence of string.
Syntax :
INSTR( String1, String2)
String or Text Functions
String or Text Functions
Example:
SELECT INSTR(“Informatics Practices”, “a”);
Output: 7
Q. Display the position of character ‘a’ in the Employee names.
Sol.: SELECT Ename , INSTR(Ename , ‘a’)
FROM Emp;
9. LTRIM( ) : This function removes leading spaces from a String.
Syntax :
LTRIM( String)
Example:
SELECT LTRIM(“ INFORMATION TECH”);
Output: INFORMATION TECH
String or Text Functions
String or Text Functions
10. RTRIM( ) : This function removes trailing spaces from a String.
Syntax :
RTRIM( String)
Example:
SELECT RTRIM(“ INFORMATION TECH ”);
Output: INFORMATION TECH
11. TRIM( ) : This function removes leading as well as trailing spaces from a
String.
Syntax :
TRIM( String)
Example:
SELECT TRIM(“ INFORMATION TECH ”);
Output: INFORMATION TECH
String or Text Functions
String or Text Functions
Mathematical functions accept numeric input and returns numeric
values.
1. POWER() / POW() : This function returns the value of x to the y power.
Syntax :
POWER | POW( x , y )
* Where x is the base and y is raise to the power.
Numeric or Math Functions
Numeric or Math Functions
Example:
SELECT POWER(2 , 3);
Output: 8
Q. Write the power of (4.56)3.
Sol.: SELECT POWER(4.56 , 3);
Output: 94.818816.
2. ROUND() : This function rounds numbers to a given number of digits of
precision. That means , returns the number rounded to n decimal places.
Syntax :
ROUND( Number | Column name , n)
* Where n is the decimal places.
Numeric or Math Functions
Numeric or Math Functions
Example:
SELECT ROUND(12.3457 , 2);
Output: 12.35
Note : It rounds the number or Column to n decimal places. If n is omitted , no
decimal places. If n is negative , numbers to the left of decimal point are
rounded.
Example:
SELECT ROUND(15.193 , -1)
Output: 20
3. MOD() : This function returns modulus i.e. remainder of m divided by n.
Syntax :
MOD( m , n)
* Where m is dividend and n is divisor.
Numeric or Math Functions
Numeric or Math Functions
Example:
SELECT MOD(11 , 4);
Output: 3
Example:
SELECT MOD(Salary , 500)
FROM Emp;
4. TRUNCATE() : This function truncates or chops off digits of precision from a
number.
Syntax :
TRUNCATE( Number , n)
* Where n is the decimal place. It truncates the number to n decimal place.
Numeric or Math Functions
Numeric or Math Functions
Example:
SELECT TRUNCATE(16.534 , 1);
Output: 16.5
Example:
SELECT TRUNCATE(15.79);
Output: 15
Example:
SELECT TRUNCATE(15.79 , -1);
Output: 10
1. CURDATE() : This function returns the current date.
Syntax :
CURDATE( )
Date Functions
Date Functions
Example:
SELECT CURDATE();
Output: 2020 – 08 -05
2. NOW() : This function returns the current date and time.
Syntax :
NOW( )
Example:
SELECT NOW();
Output: 2020 – 08 -05 10:37:41
3. DATE() : This function extracts the date part of a date time expression.
Syntax :
DATE( Date Time expr)
Date Functions
Date Functions
Example:
SELECT DATE(“ 2020 – 08 -05 10:37:41”);
Output: 2020 – 08 -05
4. MONTH() : This function returns the month (i.e. 1 – 12) from a date passed.
Syntax :
MONTH(Date expr )
Example:
SELECT MONTH((“ 2020 – 08 -05” );
Output: 08
5. MONTHNAME() : This function returns the month name from a date passed.
Syntax :
MONTHNAME( Date expr)
Date Functions
Date Functions
Example:
SELECT MONTHNAME(“ 2020 – 08 -05”);
Output: August
6. YEAR() : This function returns the year from a date passed.
Syntax :
YEAR(Date expr )
Example:
SELECT YEAR((“ 2020 – 08 -05” );
Output: 2020
7. DAY() : This function returns the Day of month (i.e. 1 – 31) from a date passed.
Syntax :
DAY( Date expr)
Date Functions
Date Functions
Example:
SELECT DAY(“ 2020 – 08 -05”);
Output: 05
8. DAYNAME() : This function returns the Dayname from a date passed.
Syntax :
DAYNAME(Date expr )
Example:
SELECT DAYNAME((“ 2020 – 08 -05” );
Output: Wednesday
Unit 2 : Database Query
Unit 2 : Database Query
using SQL
using SQL
Grouping Records in MySQL
“Group functions or Aggregate functions operate on sets of rows to
give one result per group.“
That means, these function work upon groups of rows, and hence are
called Multiple Row Functions.
Note: All the Group functions are used in SELECT statement.
Syntax: SELECT <Function Name>(<Parameter>)
FROM <Table Name>;
The Group functions are of following types:
(1) MIN() (2) MAX() (3) SUM() (4) AVG() (5) COUNT()
Group Functions or Aggregate Functions
Group Functions or Aggregate Functions
1. MIN() : This function returns the minimum value of a given Column or
expression, ignoring the null values.
Syntax :
MIN([DISTINCT | ALL] Column | Expr )
Group Functions or Aggregate Functions
Group Functions or Aggregate Functions
Example :
SELECT MIN(100, 50, 400, 200);
Output: 50
Q. Write a query to find the minimum salary in Emp table.
Sol. SELECT MIN(Salary)
FROM Emp;
2. MAX() : This function returns the maximun value of a given Column or
expression, ignoring the null values.
Syntax :
MAX([DISTINCT | ALL] Column | Expr )
Group Functions or Aggregate Functions
Group Functions or Aggregate Functions
Example :
SELECT MAX(100, 50, 400, 200);
Output: 400
Q. Write a query to find the maximum salary in Emp table.
Sol. SELECT MAX(Salary)
FROM Emp;
3. SUM() : This function returns the sum of values in given Column or expression,
ignoring the null values.
Syntax :
SUM([DISTINCT | ALL] Column | Expr )
Group Functions or Aggregate Functions
Group Functions or Aggregate Functions
Example :
SELECT SUM(100, 50, 400, 200);
Output: 750
Q. Write a query to find the Total salary of Employees in Emp table.
Sol. SELECT SUM(Salary)
FROM Emp;
4. AVG() : This function returns an average value of the numeric Column or
expression, ignoring the null values.
Syntax :
AVG([DISTINCT | ALL] Column | Expr )
Group Functions or Aggregate Functions
Group Functions or Aggregate Functions
Example :
SELECT AVG(100, 300, 400, 200); Output: 250
Q. Write a query to find the Average salary of Employees in Emp table.
Sol. SELECT AVG(Salary)
FROM Emp;
Q. Write a query to find Sum and Average salary of Employees working in RND
department.
Sol. SELECT Sum(Salary), AVG(Salary)
FROM Emp
WHERE Dept = “RND”;
5. COUNT() : This function counts the number of rows in the table, including
duplicates and those with nulls.
Syntax :
COUNT({ * | [DISTINCT | ALL] Expr })
Group Functions or Aggregate Functions
Group Functions or Aggregate Functions
(a)
(b)
The COUNT() function has two formats :
COUNT (*) : returns the number of rows in the table, including duplicates rows
containing NULL values in any column.
COUNT ( Expr ) : returns the number of non NULL rows in the column identified by
expr.
Group Functions or Aggregate Functions
Group Functions or Aggregate Functions
Q.
Q.
Display number of records or rows in Emp table.
Sol. SELECT COUNT(*)
FROM Emp;
Q. Display the number of department available in Emp table.
Sol. SELECT COUNT(DISTINCT Dept)
FROM Emp;
GROUP BY clause is used with the SELECT statement to divide the rows
in a table into groups.
The Groups are determined by the columns that you specify in the GROUP BY
clause and groups rows that have the same values.
The GROUP BY clause is used with Aggregate or Group functions (MIN(), MAX() ,
SUM(), AVG(), COUNT()) to group the result-set by one or more columns.
Note: All the Group functions treated the table as one large group of
information. At times, we need to divide the table of information into
groups. This can be done by using GROUP BY clause.
Grouping Records : GROUP BY clause
Grouping Records : GROUP BY clause
Grouping Records : GROUP BY clause
Grouping Records : GROUP BY clause
Table – Emp
Table – Emp
Table – Emp
Table – Emp
Table – Emp
Ecode Ename Dept City Gender Salary
1001 A. Williams Production Ahmedabad M 46000
1002 Sanjeev Batra Personnel Jalandhar M 30000
1003 Ishita Sharma RND New Delhi F 50000
1004 Suresh Baroth RND Jaipur M 55000
1005 Seema Sharma Marketing Shimla F 36500
1006 Akram Hussain Servicing Hamirpur M 20000
1007 Dhiraj Patel Production Surat M 45000
1008 Meera Kumari RND Phagwara F 40000
Q.1. Display the total salary offered to each Department.
Sol. SELECT Dept, SUM(Salary)
FROM Emp
GROUP BY Dept;
Output:
Grouping Records : GROUP BY clause
Grouping Records : GROUP BY clause
Grouping Records : GROUP BY clause
Grouping Records : GROUP BY clause
Dept SUM(Salary)
Production 91000
Personnel 30000
RND 145000
Marketing 36500
Servicing 20000
Q.2. Display the maximum and minimum Salary of Employees
Department wise for RND department.
Sol. SELECT Dept, MAX(Salary), MIN(Salary)
FROM Emp
WHERE Dept = ‘RND’
GROUP BY Dept;
Output:
Grouping Records : GROUP BY clause
Grouping Records : GROUP BY clause
Grouping Records : GROUP BY clause
Grouping Records : GROUP BY clause
Dept MAX(Salary) MIN(Salary)
RND 55000 40000
HAVING clause can be used to restrict groups on the basis of Aggregate
or Group function.
The MySQL performs the following steps when we use the HAVING clause:
Rows are grouped
The group function is applied to the group
The groups that match the criteria in the HAVING clause are displayed
Excluding Group Results : HAVING clause
Excluding Group Results : HAVING clause
Excluding Group Results : HAVING clause
Excluding Group Results : HAVING clause
Q. Display the average salary of Employees Department wise, whose average
salary more than 30000
Sol. SELECT Dept, AVG(Salary)
FROM Emp
GROUP BY Dept
HAVING AVG(Salary) > 30000;
Illegal Queries with GROUP BY Clause
Q. Display the average salary of Employees Department wise, whose
average salary more than 30000
Sol. SELECT Dept, AVG(Salary)
FROM Emp
WHERE AVG(Salary) >30000
GROUP BY Dept;
Output: ERROR 1111
Q. Display the Total salary of Employees Department wise and
display only those rows having Total salary more than 60000.
Excluding Group Results : HAVING clause
Excluding Group Results : HAVING clause
Excluding Group Results : HAVING clause
Excluding Group Results : HAVING clause
Please send your feedback to arvindsingh.
dav@gmail.com
Whatsapp : 98358 11914
Thanks
Thanks

More Related Content

Similar to Database Concepts & SQL(1).pdf

Database Management System, Lecture-1
Database Management System, Lecture-1Database Management System, Lecture-1
Database Management System, Lecture-1Sonia Mim
 
Database management system by Gursharan singh
Database management system by Gursharan singhDatabase management system by Gursharan singh
Database management system by Gursharan singhGursharan Singh
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxKoteswari Kasireddy
 
Database-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptxDatabase-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptxAnmolThakur67
 
DBMS Full book by Muhammad Sharif title as Database systems Handbook.pdf
DBMS Full book by Muhammad Sharif  title as Database systems Handbook.pdfDBMS Full book by Muhammad Sharif  title as Database systems Handbook.pdf
DBMS Full book by Muhammad Sharif title as Database systems Handbook.pdfBahria University Islamabad, Pakistan
 
csedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfcsedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfSameerKhanPathan7
 
Ch-1-Introduction-to-Database.pdf
Ch-1-Introduction-to-Database.pdfCh-1-Introduction-to-Database.pdf
Ch-1-Introduction-to-Database.pdfMrjJoker1
 
Spatial Database and Database Management System
Spatial Database and Database Management SystemSpatial Database and Database Management System
Spatial Database and Database Management SystemLal Mohammad
 
COMPUTERS Database
COMPUTERS Database COMPUTERS Database
COMPUTERS Database Rc Os
 
Introduction to Database Management System
Introduction to Database Management SystemIntroduction to Database Management System
Introduction to Database Management SystemHitesh Mohapatra
 

Similar to Database Concepts & SQL(1).pdf (20)

Database Management System, Lecture-1
Database Management System, Lecture-1Database Management System, Lecture-1
Database Management System, Lecture-1
 
Database management system by Gursharan singh
Database management system by Gursharan singhDatabase management system by Gursharan singh
Database management system by Gursharan singh
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptx
 
Database systems Handbook 2V.pdf
Database systems Handbook 2V.pdfDatabase systems Handbook 2V.pdf
Database systems Handbook 2V.pdf
 
Dbms
DbmsDbms
Dbms
 
Database systems Handbook.pdf
Database systems Handbook.pdfDatabase systems Handbook.pdf
Database systems Handbook.pdf
 
Database systems Handbook.pdf
Database systems Handbook.pdfDatabase systems Handbook.pdf
Database systems Handbook.pdf
 
Database systems Handbook dbms.pdf
Database systems Handbook dbms.pdfDatabase systems Handbook dbms.pdf
Database systems Handbook dbms.pdf
 
Database systems Handbook dbms.pdf
Database systems Handbook dbms.pdfDatabase systems Handbook dbms.pdf
Database systems Handbook dbms.pdf
 
Database systems Handbook dbms.pdf
Database systems Handbook dbms.pdfDatabase systems Handbook dbms.pdf
Database systems Handbook dbms.pdf
 
Database-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptxDatabase-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptx
 
DBMS Full book by Muhammad Sharif title as Database systems Handbook.pdf
DBMS Full book by Muhammad Sharif  title as Database systems Handbook.pdfDBMS Full book by Muhammad Sharif  title as Database systems Handbook.pdf
DBMS Full book by Muhammad Sharif title as Database systems Handbook.pdf
 
Muhammad Sharif dbms book title as Database systems Handbook.pdf
Muhammad Sharif dbms book title as Database systems Handbook.pdfMuhammad Sharif dbms book title as Database systems Handbook.pdf
Muhammad Sharif dbms book title as Database systems Handbook.pdf
 
Muhammad Sharif dbms book title as Database systems Handbook.pdf
Muhammad Sharif dbms book title as Database systems Handbook.pdfMuhammad Sharif dbms book title as Database systems Handbook.pdf
Muhammad Sharif dbms book title as Database systems Handbook.pdf
 
Database Management System ppt
Database Management System pptDatabase Management System ppt
Database Management System ppt
 
csedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdfcsedatabasemanagementsystemppt-170825044344.pdf
csedatabasemanagementsystemppt-170825044344.pdf
 
Ch-1-Introduction-to-Database.pdf
Ch-1-Introduction-to-Database.pdfCh-1-Introduction-to-Database.pdf
Ch-1-Introduction-to-Database.pdf
 
Spatial Database and Database Management System
Spatial Database and Database Management SystemSpatial Database and Database Management System
Spatial Database and Database Management System
 
COMPUTERS Database
COMPUTERS Database COMPUTERS Database
COMPUTERS Database
 
Introduction to Database Management System
Introduction to Database Management SystemIntroduction to Database Management System
Introduction to Database Management System
 

Recently uploaded

ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 

Recently uploaded (20)

ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 

Database Concepts & SQL(1).pdf

  • 1. Informatics Practices (IP) Informatics Practices (IP) Informatics Practices (IP) By Arvind Sir
  • 2. Unit 3 : Database Concepts and SQL Unit 3 : Database Concepts and SQL Unit 3 : Database Concepts and SQL
  • 3. “Database is an organized collection of related information stored in easily accessible form which are integrated, shared and used for multiple purposes”. Database Technology is one of the most rapidly growing fields of Computer Science. It is a computer based record keeping system, whose overall purpose is to record and to maintain large volume of information that is necessary for Organization management. In this technology, the contents of database are obtained by combining data from all the different sources, So that data are available to all Users to access and manipulate database. Database Concepts Database Concepts
  • 4. Advantages of Databases: Data Redundancy is reduced Data Inconsistency is controlled Sharing of Data Data Security Data Integrity Database Concepts Database Concepts
  • 5. A Database Management System is an integrated set of programs or Software designed to store, modify, delete and extract information from a database. In other words, It is a collection of programs that enables users to create, maintain and control all the access to database. Some DBMS software are : FoxBASE, FoxPro, Sybase, MS-Access, ORACLE, MySQL etc. DBMS offers the following services: Data Definition: It is a method of defining data and storage. Data Maintenance: It checks whether each record has field containing all information for a particular record or not. Data Manipulation: It allows data in the database to be inserted, updated, deleted and stored. Data Display: It helps in viewing data. Data Integrity: It ensures the accuracy of the data. Database Management System (DBMS) Database Management System (DBMS)
  • 6. DBMS involves four major components: Data, Hardware, Software and Users. Data : The data stored in a system is partitioned into one or more database that contains both the actual or operational data and the metadata. Generally, it is both integrated and shared. DBMS exists to collect, store, process and access data. Hardware: The hardware consists of a set of physical electronic devices such as computers, I/O devices, storage devices(on which the database resides together with the associated devices), etc. This provides the interface between computers and the real world systems. Software: This is the set of programs used to control and manage the overall database. This includes the DBMS software itself, the Operating System, the network software being used to share the data among users, and the application programs used to access data in the DBMS. Components of DBMS
  • 7. Users : There are three broad categories of users: the Application Programmer, the End-User and the Database Administrator(DBA). Application Programmer : The Application Programmer is responsible for writing Application programs that use the database. These application programs operate on the data in all the usual ways i.e. Retrieving information, creating new information, deleting or modifying existing information. All these functions are performed by issuing the appropriate requests to the DBMS. End-User : An End-User may employ a query language provided as integral part of the system, or may invoke a user-written application program that accepts commands from the terminal and the End-User may perform all the functions of retrieval, creation, deletion and modification. Database Administrator : DBA is to decide what information will be held in the database to identify the information to be recorded about the entities. Components of DBMS
  • 8. Data model is an integrated collection of concepts that can be used for describing the structure of the database and manipulating data, relationships between data and constraints on the data in an organization. That means, a database model shows the logical structure of a database, including the relationships and constraints that determine how data can be stored and accessed. In fact, Data models define how data is connected to each other and how they are processed and stored inside the system. Different types of database models were introduced on the basis of the DBMS implementations. These are referred to as : 1. Hierarchical Data Model 2. Network Data Model 3. Relational Data Model Database Models
  • 9. 1. Hierarchical Data Model : The hierarchical model was one of the earliest data model. This model organizes data into a tree-like structure, where each record has a single parent or root and can be used to construct a hierarchy of records in the form of nodes and branches. In the above example the root record represents some product i.e. shoes which is composed of part Women’s shoes and Men’s shoes, each of these are composed of subparts like High Heels, Bellies, sports shoes, Sneakers etc. This model does not support many-to-many relationship because the links in hierarchical model are unidirectional i.e. we can travel parent to the child only. So if we need any information from lower level then we have to follow complete hierarchy of the system. Database Models
  • 10. 2. Network Data Model : The Network data model can be equated with a network file structure which supports all relationship restricted to be either binary or many- one relationships. In this structure it is possible for one node to share ownership of a model at a lower level with another node in a separate branch of a tree. In Network model, the data is represented by collections of records and relationships among data are represented as links. Database Models
  • 11. 3. Relational Data Model : The Relational model is developed by (IBM’s) Dr. E. F. Codd in 1969. This model is based on the concept that data is organized and stored in two-dimensional tables called relations. A Relational model consists of a collection of tables, each of which is assigned a unique name, i.e. it represents the database as a collection of relations or tables with rows (record) and columns (fields). The rows of a relation are called Tuples (pronounced to rhyme with “Couple”) and the columns of a relation are called Attributes. Relational data model is the data model, which is used widely around the world for data storage and processing. This model is simple and it has all the properties and capabilities required to process data with storage efficiency. Database Models
  • 12. The Relational data model eliminated all parent-child relationships and instead represented all data in the database as simple row/column tables of data values. A relation is similar to a table with rows / columns of data values. The rows of a table are referred to as Tuples and the columns are referred to as Attributes. Several tuples of equal length placed one below the other create a table. Each table is am independent entity and there is no physical relationship between a table. Relational model of data management is based on set theory. Built-in query language is designed in the RDBMS, so that it can manipulate set of data (one or more tuples) The user interface used with relational models in non-procedural, because only what needs to be done is specified and not how it has to be done. Characteristics of a Relational DBMS Model
  • 13. The components used in Relational model are outlined as follows: Entities Attributes Relationships Entities: Entities are the fundamental building blocks of Relational Database design. An entity defines any person, place, thing or concept for which data will be collected. For example : Components of a Relational Model Person Student, Teacher Place Classroom Thing Computer (Lab equipment) Concept Study
  • 14. Attributes : Attributes are additional characteristics or information for an entity. An attribute describes a property associated with entities. It will have a name and a value for each entity. For example, Rollno, Name, Address, Pincode, etc. These attributes can be defined for a student. A specific student will have value for each of these attributes. Relationships : A Relationship is a logical linkage between two entities that describes how the entities are associated with each other. For example: One- to–one relationship One-to-many or Many-to-one relationship Many-to-many relationship Components of a Relational Model
  • 15. Objects Description Relation (Table) A relation is a table with rows and columns. Tuple (Row, Record) A tuple is a row in a relation. Attribute (Column, Field) Attribute is the named column of a relation. Domain (set of legal values) A domain is the set of allowable values for one or more attributes. Degree (Number of columns) The degree of a relation is the number of attributes it contains. Cardinality (Number of rows) The cardinality of a relation is the number of tuples it contains. RDBMS Terminology
  • 16. A key allows us to identify a set of attributes that distinguishes entities from each other. Primary Key Foreign Key Candidate Key Alternate Key Primary Key: A Primary Key is a set of one or more attributes or columns that are uniquely identify tuples within the relation. The Primary key values should never be changed and should never be null. For example, Stud_ID, RollNo, AdmNo etc. Foreign Key : A Foreign key is a column or group of columns whose values are derived from the Primary key of another table. It represents relationships between two or more tables. When relationship is created between two or more tables, the Master table contributes its Primary key to the Transaction table which is known as Foreign key. Keys in MySQL
  • 17. Candidate Key: All attributes inside a relation that can serve as Primary key are Candidate key as they are candidates for Primary key. Following are the important differences between Primary Key and Candidate key Keys in MySQL Sr. No. Key Primary Key Candidate key 1 Definition Primary Key is a unique and non-null key which identify a record uniquely in table. A table can have only one primary key. Candidate key is also a unique key to identify a record uniquely in a table but a table can have multiple candidate keys. 2 Null Primary key column value can not be null. Candidate key column can have null value. 3 Objective Primary key is most important part of any relation or table. Candidate key signifies as which key can be used as Primary Key. 4 Use Primary Key is a candidate key. Candidate key may or may not be a primary key.
  • 18. AlternateKey: A candidate key not selected as a primary key is called alternate or secondary key. That means, any attribute that is the candidate for the primary key but is not Primary key is called Alternate key. Let us see an example − Above, Student_ID, Student_Enroll and Student_Email are the candidate keys. They are considered candidate keys since they can uniquely identify the student record. Select any one of the candidate key as the primary. Rest of the two keys would be Alternate or Secondary Key. Let’s say you selected Student_ID as primary key, therefore Student_Enroll and Student_Email will be Alternate Key (candidates of primary key). Keys in MySQL Student_ID Student_Enroll Student_Name Student_Email 096 2717 Manish aaa@gmail.com 055 2655 Manan abc@gmail.com 067 2699 Shreyas pqr@gmail.com
  • 19. MySQL stands for “My Structured Query Language”. MySQL is an open source and freely available Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). It provides excellent features for creating, storing, maintaining and accessing data stored in the form of Databases and their respective tables. MySQL was developed by the company MYSQL AB founded in Sweden. At first, MySQL was not intended to be a commercial product. Sun Micro Systems aquired MYSQL AB in 2008, which holds the copyright. It is fully secured reliable and possesses better functionalities than many other commercial RDBMS. Inventer: Michael Widenius “Monty”, David Axmark & Allan Larson Overview of MySQL Overview of MySQL
  • 20. Cost : MySQL is open source and is available free of cost. Performance : MySQL is very fast, because it supports clustered servers for demanding applications. Easy to use : MySQL is high performance relatively simple database system. Simplicity : MySQL is easy to install. Data Security : MySQL has powerful mechanisms for ensuring only authorized users have access, support for safe and secure connections, powerful data encryptions & decryption functions. Application Support : MySQL has an API for just about any programming language. Specifically, we can write database applications that access MySQL in C, C++, Java etc. Features of MySQL Features of MySQL
  • 21. SQL ( pronounced “ess – que – el” or “sequel” ) stands for Structured Query Language. SQL is the most common standard language for accessing and manipulating databases. It is fourth generation non – procedural language that is used to create, manipulate and process the databases. SQL was originated by Donald D. Chamberlin and Raymond F. Boyce in 1974 at IBM’s Son Jose Research Centre and standardized by ANSI (American National Standards Institutes) and ISO (International Standard Organization) in 1986. SQL has emerged as Standard Language for relational DBMS and most commercial Relational Database Management System use SQL. The key features of SQL are: Non – procedural Language Unified Language Common language for all Relational Databases Introduction to SQL Introduction to SQL
  • 22. SQL (Structured Query Language) is made of four sub languages as follows : Data Definition Language (DDL) Data Manipulation Language (DML) Transaction Control Language (TCL) Classification of SQL Commands
  • 23. Creating Database - CREATE DATABASE Viewing a List of Databases - SHOW DATABASES Accessing Database – USE Viewing a List of Tables - SHOW TABLES Creating Table – CREATE TABLE Viewing a Table Structure - DESCRIBE Inserting Data into Table – INSERT INTO Making Simple Queries – SELECT Modifying Data in Tables – UPDATE Deleting Data from Tables – DELETE Altering Tables – ALTER TABLE Dropping Tables – DROP TABLE SQL Commands SQL Commands
  • 24. Syntax : CREATE DATABASE <Database Name>; Example : Mysql> CREATE DATABASE Employee ; Database created Mysql> SHOW DATABASES ; Creating Database - CREATE DATABASE Creating Database - CREATE DATABASE Creating Database - CREATE DATABASE
  • 25. Syntax : USE <Database Name>; Example : Mysql> USE Employee ; Database changed Mysql> SHOW TABLES ; Accessing Database – USE Accessing Database – USE Accessing Database – USE
  • 26. Syntax : CREATE TABLE <Table_name > ( Column1 Datatype(Size), Column2 Datatype(Size), Column3 Datatype(Size) ); Example: Create a table Emp with the following structure Creating Tables – CREATE TABLE Creating Tables – CREATE TABLE Creating Tables – CREATE TABLE Column Name Data Type Size Ecode INT 4 Ename VARCHAR 30 Dept VARCHAR 12 City VARCHAR 15 Gender CHAR 1 Salary FLOAT 7,2
  • 27. Mysql> CREATE TABLE Emp ( Ecode INT(4), Ename VARCHAR(30), Dept VARCHAR(12), City VARCHAR(15), Gender CHAR(1), Salary FLOAT(7,2) ); Creating Tables – CREATE TABLE Creating Tables – CREATE TABLE Creating Tables – CREATE TABLE Column Name Data Type Size Ecode INT 4 Ename VARCHAR 30 Dept VARCHAR 12 City VARCHAR 15 Gender CHAR 1 Salary FLOAT 7,2
  • 28. “Constraints are rules that can be used to control the invalid data entry in a column.” Constraints are a part of the table definition that limit the values entered into its column. Some common types of Constraints are : NOT NULL UNIQUE PRIMARY KEY DEFAULT CHECK FOREIGN KEY SQL Constraints SQL Constraints
  • 29. 1. NOT NULL Constraint: The NOT NULL Constraints ensure that the user always type the value for that column i. e. the column becomes a mandatory column. That means NOT NULL specifies that a column must have some value. Example : Gender CHAR(1) NOT NULL; 2. UNIQUE Constraint: The UNIQUE Constraints ensure that the value for that column is unique or distinct. That means the value entered in UNIQUE column must not be repeated across the column. Note: UNIQUE key can be NULL at the time of data entry, So value is not mandatory for UNIQUE column. Example : Ecode INT(4) UNIQUE; SQL Constraints SQL Constraints
  • 30. 3. PRIMARY KEY Constraint: The PRIMARY KEY Constraints specifies that the column(s) in the table are prime key and must have unique value across the column and column can’t be le left blank. Example : Ecode INT(4) PRIMARY KEY; 4. DEFAULT Constraint: The DEFAULT Constraints specifies a default value to the column if no value entered by the user. Default value can be assigned to a column at the time of table creation. Example : City VARCHAR(15) DEFAULT = ‘Patna’; SQL Constraints SQL Constraints
  • 31. 5. CHECK Constraint: The CHECK Constraints ensure that when data is entered, the data in the column is limited to specific value that satisfy certain criteria or condition. Example : Category VARCHAR(4) CHECK Category IN(‘SC’, ‘ST’, ‘OBC’,’GEN); 6. FOREIGN KEY Constraint: The FOREIGN KEY Constraint is used to represent relationship between two or more tables. The FOREIGN KEY is defined in the child table containing the referenced column Example : FOREIGN KEY(Ecode) REFERENCES Emp(Ecode); SQL Constraints SQL Constraints
  • 32. Syntax : CREATE TABLE <Table_name > ( Column1 Datatype(Size) [Constraint], Column2 Datatype(Size) [Constraint], Column3 Datatype(Size) [Constraint] ); Example: Create a table Emp with the following structure Creating Tables with SQL Constraints – CREATE TABLE Creating Tables with SQL Constraints – CREATE TABLE Creating Tables with SQL Constraints – CREATE TABLE Creating Tables with SQL Constraints – CREATE TABLE Column Name Data Type Size Constraints Ecode INT 4 PRIMARY KEY Ename VARCHAR 30 Dept VARCHAR 12 City VARCHAR 15 Gender CHAR 1 NOT NULL Salary FLOAT 7,2 Column Name Data Type Size Constraints Ecode INT 4 PRIMARY KEY Ename VARCHAR 30 Dept VARCHAR 12 City VARCHAR 15 Gender CHAR 1 NOT NULL Salary FLOAT 7,2
  • 33. Mysql> CREATE TABLE Emp ( Ecode INT(4) PRIMARY KEY, Ename VARCHAR(30), Dept VARCHAR(12), City VARCHAR(15), Gender CHAR(1) NOT NULL, Salary FLOAT(7,2) ); Creating Tables with SQLConstraints – CREATE TABLE Creating Tables with SQLConstraints – CREATE TABLE Creating Tables with SQLConstraints – CREATE TABLE Creating Tables with SQLConstraints – CREATE TABLE Column Name Data Type Size Constraints Ecode INT 4 PRIMARY KEY Ename VARCHAR 30 Dept VARCHAR 12 City VARCHAR 15 Gender CHAR 1 NOT NULL Salary FLOAT 7,2
  • 34. This command is used to display the structure of the table. ( i. e. this command display column names and data types as well as whether a column must contain data). Syntax : DESC / DESCRIBE <Table Name>; Example : Mysql> DESC Emp; OR Mysql> DESCRIBE Emp; Displaying Table Structure – DESCRIBE or DESC Displaying Table Structure – DESCRIBE or DESC Displaying Table Structure – DESCRIBE or DESC
  • 35. This command is used to insert the data into the table. Insert operation: Creates a new row in the table. Stores the values passed into the column field. Note: using the INSERT command only one row is inserted at a time. Syntax : INSERT INTO <Table Name> [ <Column List> ] VALUES ( value 1, value 2, ………….. ) ; Example 1: Mysql> INSERT INTO Emp VALUES(1001, “A. Williams”, “Production”, “Ahmedabad”, “M”,46000); Inserting Data into Table – INSERT INTO Inserting Data into Table – INSERT INTO Inserting Data into Table – INSERT INTO
  • 36. Example 2: To insert data only in specific columns i. e. Ecode, Ename and Gender columns. Mysql> INSERT INTO Emp (Ecode, Ename, Gender) VALUES(1002, “Kuldip”, “M”); OR Mysql> INSERT INTO Emp VALUES(1002, “Kuldip”, NULL, NULL,“M”, NULL); Inserting Data into Table – INSERT INTO Inserting Data into Table – INSERT INTO Inserting Data into Table – INSERT INTO
  • 37. Insert the following Data into the Table – Emp Insert the following Data into the Table – Emp Insert the following Data into the Table – Emp Insert the following Data into the Table – Emp Ecode Ename Dept City Gender Salary 1001 A. Williams Production Ahmedabad M 46000 1002 Sanjeev Batra Personnel Jalandhar M 30000 1003 Ishita Sharma RND New Delhi F 50000 1004 Suresh Baroth RND Jaipur M 55000 1005 Seema Sharma Marketing Shimla F 36500 1006 Akram Hussain Servicing Hamirpur M 20000 1007 Dhiraj Patel Production Surat M 45000 1008 Meera Kumari RND Phagwara F 40000
  • 38. A SELECT command retrieves information from the table. Using a SELECT command, we can do the following: Selection : The selection capability in SQL can use to choose the rows in a table that we want returned by a query. We can use criteria or condition to selectively restrict the rows that we see. Projection : The projection capability in SQL can use to choose the columns in a table that we want returned by a query. We can choose as many columns of the table as we require. Join : The join capability in SQL can use to bring together data stored in different tables by creating a link between them. Displaying Information from the Table - SELECT Displaying Information from the Table - SELECT Displaying Information from the Table - SELECT
  • 39. Syntax : SELECT [ DISTINCT <Column Name> ] { * | <Column List> [Alias] } FROM <Table Name> ; [ WHERE <Condition> ] [ ORDER BY <Column Name> ASC | DESC ] Making Simple Queries – SELECT Making Simple Queries – SELECT Making Simple Queries – SELECT In the Syntax : SELECT is a list of one or more columns DISTINCT eliminates duplicates across the given column * Selects all columns Column List selects the specified column Alias gives selected columns different Headings Uses: <Old column name> AS < New column name > FROM <Table> specifies the table containing the columns
  • 40. Consider the following Data into the Table – Emp Consider the following Data into the Table – Emp Consider the following Data into the Table – Emp Consider the following Data into the Table – Emp Ecode Ename Dept City Gender Salary 1001 A. Williams Production Ahmedabad M 46000 1002 Sanjeev Batra Personnel Jalandhar M 30000 1003 Ishita Sharma RND New Delhi F 50000 1004 Suresh Baroth RND Jaipur M 55000 1005 Seema Sharma Marketing Shimla F 36500 1006 Akram Hussain Servicing Hamirpur M 20000 1007 Dhiraj Patel Production Surat M 45000 1008 Meera Kumari RND Phagwara F 40000
  • 41. 1. Selecting All Columns : Syntax: SELECT * FROM <Tablename>; Example: Mysql> SELECT * FROM Emp; The output of this command would be to display the whole table because * has selected all columns. 2. Selecting Specific Columns : Syntax: SELECT < List of columns> FROM <Tablename>; Example: Mysql> SELECT Ecode, Ename, Salary FROM Emp; The output of this command would be to display the information of three columns (i. e. Ecode, Ename and Salary) of table Emp. Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command
  • 42. 4. 3. Eliminating Duplicate Data (DISTINCT Keyboard): Syntax: SELECT DISTINCT <Column Name> FROM <Tablename>; Example: Mysql> SELECT DISTINCT Dept FROM Emp; Using Arithmetic Operators: Example 1: Mysql> SELECT Ecode, Ename, Salary + 500 FROM Emp; Example 2: Mysql> SELECT 2 + 5; Output: 7 Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command Working with Emp Table using SELECT command
  • 43. Syntax : SELECT [ DISTINCT <Column Name> ] { * | <Column List> [Alias] } FROM <Table Name> WHERE <Condition> ; The WHERE Clause with SELECT Command The WHERE Clause with SELECT Command The WHERE Clause with SELECT Command The WHERE Clause with SELECT Command The WHERE Clause with SELECT Command In the Syntax : WHERE restricts the query to rows that meet a condition <Condition> is composed of column names, expressions, constants and a comparison or relational operator. * The WHERE clause consists of three elements : 1. Column Name 2. Comparison operator 3.Constant or list of values The WHERE clause is used along with the SELECT command to specify the condition or criteria , based on which row will be extracted from the table. Note : WHERE clause examines each row to determine if the condition is true with respect to the row.
  • 44. Q. 1. Display the Name and Department of those Employees where department is Production. Sol.: SELECT Ename, Dept FROM Emp WHERE Dept = “Production” ; Q. 2. Display the Name and Salary of those Employees whose salary is more than 40, 000. Sol.: SELECT Ename, Salary FROM Emp WHERE Salary > 40000 ; Q. 2. Display the Name of female Employees in the table. Sol.: SELECT Ename FROM Emp WHERE Gender = ‘F’; Working with Emp Table using WHERE clause Working with Emp Table using WHERE clause Working with Emp Table using WHERE clause Working with Emp Table using WHERE clause Working with Emp Table using WHERE clause Working with Emp Table using WHERE clause Working with Emp Table using WHERE clause
  • 45. Q. 4. Display the Name and Department of Employees working in Production and servicing Department. Sol.: SELECT Ename, Dept FROM Emp WHERE Dept = “Production” OR Dept = “Servicing” ; Q. 5. Display the Ecode, City and Salary of those Employees who are living in Jalandhar and have salary greater than 20,000. Sol.: SELECT Ename, City, Salary FROM Emp WHERE City = ‘Jalandhar’ AND Salary > 20000 ; Q. 6. Display the Name of Employees who are not females. Sol.: SELECT Ename FROM Emp WHERE Gender != ‘F’; The WHERE clause with Logical Operators The WHERE clause with Logical Operators The WHERE clause with Logical Operators The WHERE clause with Logical Operators The WHERE clause with Logical Operators The WHERE clause with Logical Operators
  • 46. Q. 7. Display the details of Employees, whose Salary is between 40,000 and 50,000. Sol.: SELECT * FROM Emp WHERE Salary BETWEEN 40000 AND 50000; Q. 8. Display the code, names of the Employees having Ecode 1001, 1004 and 1008. Sol.: SELECT Ecode, Ename FROM Emp WHERE Ecode IN(1001, 1004, 1008); Q. 9. Display the Name of Employees who live in city Jalandhar, New Delhi or Ahmedabad. Sol.: SELECT Ename FROM Emp WHERE City IN (‘Jalandhar’, ‘New Delhi’, ‘Ahmedabad’); The WHERE clause with Special Operators The WHERE clause with Special Operators The WHERE clause with Special Operators The WHERE clause with Special Operators The WHERE clause with Special Operators The WHERE clause with Special Operators
  • 47. LIKE Operator : The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. It determines if a character string matches a specified pattern (i. e. regular character and wildcard characters) to filter row based on pattern matching. In other words LIKE operator is used to perform wildcard ( match a character pattern ) searches of String values. There are two wildcard symbols used in conjunction with LIKE operator: The WHERE clause with Special Operators The WHERE clause with Special Operators The WHERE clause with Special Operators The WHERE clause with Special Operators The WHERE clause with Special Operators The WHERE clause with Special Operators Symbol Description % (Percent) Represents any sequence of zero or more characters. _ (Underscore) Represents any single character.
  • 48. Q. 1. Display the Name of Employees, whose Names start with “S”. Sol.: SELECT Ename FROM Emp WHERE Ename LIKE “S%”; Q. 2. Display the Ecode and Name of Employees, whose Names ending with “a”. Sol.: SELECT Ecode, Ename FROM Emp WHERE Ename LIKE ‘%a’; Q. 3. Display the Name of Employees whose Names having ‘e’ as the third character. Sol.: SELECT Ename FROM Emp WHERE Ename LIKE “_ _e%”; The WHERE clause with LIKE Operators The WHERE clause with LIKE Operators The WHERE clause with LIKE Operators The WHERE clause with LIKE Operators The WHERE clause with LIKE Operators The WHERE clause with LIKE Operators
  • 49. IS NULL Operator : The IS NULL operator tests for values that are NULL. NULL value is different from assigning a column with the value 0 or a blank. It cannot be compared using the relational and logical operator. A NULL value means value is unavailable unknown or inapplicable. The WHERE clause with IS NULL Operators The WHERE clause with IS NULL Operators The WHERE clause with IS NULL Operators The WHERE clause with IS NULL Operators The WHERE clause with IS NULL Operators The WHERE clause with IS NULL Operators Q. 3. Display the Name of Employees not assigned to any department. Sol.: SELECT Ename FROM Emp WHERE Dept IS NULL;
  • 50. ORDER BY clause: The ORDER BY clause can be used with SELECT command to sort or arrange the rows according to the values in one or more selected column in Ascending or Descending order . The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command Syntax : SELECT [ DISTINCT <Column Name> ] { * | <Column List> [Alias] } FROM <Table Name> [ WHERE <Condition> ] [ ORDER BY <Column Name> ASC | DESC ] ; In the syntax: ORDER BY Specifies the order in which the retrieved rows are displayed. ASC Sorts the rows in ascending order. (By default) DESC Sorts the rows in descending order.
  • 51. Q. 1. Display Employees code, name and salary in ascending order of salary. Sol.: SELECT Ecode , Ename , Salary FROM Emp ORDER BY Salary; Q. 2. Display Employees code, name and salary in descending order of salary. Sol.: SELECT Ecode, Ename FROM Emp ORDER BY Salary DESC; Q. 3. Display Employees name and salary in descending order of salary, whose salary is more than 40000. Sol.: SELECT Ename , Salary FROM Emp WHERE Salary > 40000 ORDER BY Salary DESC; The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command The ORDER BY clause with SELECT Command
  • 52. The UPDATE command modifies the values of one or more columns in selected rows of a table. Syntax : UPDATE <Table Name> SET <Column Name> = <value> [ WHERE <Condition> ] ; Modifying Data in Tables – UPDATE Command Modifying Data in Tables – UPDATE Command Modifying Data in Tables – UPDATE Command In the syntax: UPDATE Change the values on all table rows that satisfy condition. SET Specifies which column are to be updated with given value. WHERE Selects the rows of the table to be modified. NOTE : UPDATE sets each column name equal to the corresponding value in the row selected by the condition.
  • 53. Q. 1. Increase every Employees salary by 10%. Sol.: UPDATE Emp SET Salary = Salary + Salary * 0.1; Q. 2. Change the department of Ishita Sharma to Servicing Sol.: UPDATE Emp SET Dept = ‘Servicing’ WHERE Ename = ‘Ishita Sharma’; Modifying Data in Tables – UPDATE Command Modifying Data in Tables – UPDATE Command Modifying Data in Tables – UPDATE Command Modifying Data in Tables – UPDATE Command
  • 54. The DELETE command removes existing rows from a table. Syntax : DELETE FROM <Table Name> [ WHERE <Condition> ] ; Deleting rows from Tables – DELETE Command Deleting rows from Tables – DELETE Command Deleting rows from Tables – DELETE Command NOTE : DELETE command removes only rows from the table but cannot removes columns..
  • 55. Q. 1. Delete all the records of RND Department. Sol.: DELETE FROM Emp WHERE Dept = ‘RND’; Q. 2. Delete all the records of Employees having Salary less than 40000. Sol.: DELETE FROM Emp WHERE Salary < 40000; Q. 3. Delete all records from the table. Sol.: DELETE FROM Emp; Deleting rows from Tables – DELETE Command Deleting rows from Tables – DELETE Command Deleting rows from Tables – DELETE Command
  • 56. The ALTER TABLE command is used to modify or to change the structure of the existing table. Tables can be altered in one of the three ways: By adding a new column By changing a column’s definition By dropping a column Altering Tables – ALTER TABLE Altering Tables – ALTER TABLE Altering Tables – ALTER TABLE
  • 57. We can add a new column to a table by using ALTER TABLE command with the ADD clause. Syntax : ALTER TABLE <Table Name> ADD <Column Name Datatype(size)>; Adding a new column in a table Adding a new column in a table Q. Add a column to the existing table EMP which will hold the Grades for each Employee. Sol.: ALTER TABLE Emp ADD Grade VARCHAR(6); * The new column becomes the last column. * Verify the adding by using DESCRIBE or DESC Command.
  • 58. We can modify a column definition by using ALTER TABLE command with the MODIFY clause. Column modification can include changes to a column’s Datatype and Size. Syntax : ALTER TABLE <Table Name> MODIFY (<Column Name Datatype(size)>); Modifying a column in a table Modifying a column in a table Q. Modify the Salary column with DECIMAL datatype having Size 10. Sol.: ALTER TABLE Emp MODIFY (Salary DECIMAL(10)); * Verify the result of using DESCRIBE or DESC Command.
  • 59. 1. 2. We can drop or remove a column from a table by using ALTER TABLE command with the DROP COLUMN clause. The column may or may not contain data. Only one column can be dropped at a time. Syntax : ALTER TABLE <Table Name> DROP COLUMN <Column Name >; Dropping a column in a table Dropping a column in a table Q. Remove the Grade column from the table. Sol.: ALTER TABLE Emp DROP COLUMN Grade; * The Grade column will be deleted.
  • 60. We can change a column heading to a table by using ALTER TABLE command with the CHANGE clause. Syntax : ALTER TABLE <Table Name> CHANGE <Old Column Name > <New Column Name Definition >; Changing a column heading in a table Changing a column heading in a table Q. Change the name of column Dept as Department. Sol.: ALTER TABLE Emp CHANGE Dept Department VARCHAR(15);
  • 61. The DROP TABLE command is used to remove the entire table along with its structure permanently from the Database. Dropping Table – DROP TABLE Dropping Table – DROP TABLE Dropping Table – DROP TABLE Syntax : DROP TABLE <Table Name> ; Q. Remove the table EMP along with its structure. Sol.: DROP TABLE Emp;
  • 62. Unit 2 : Database Query Unit 2 : Database Query using SQL using SQL Functions in MySQL
  • 63. 1. “A function is a set of predefined commands that performs specific operation and returns value(s). “ MySQL functions may accept argument and always return a value. The functions used in SQL can be categorised into two categories: 1. Single Row Functions or Scalar Functions 2. Multi Row Functions or Aggregate functions Single Row Functions: The single Row Functions work with a single row at a time and return one result per row. Example: String Functions Mathematical of Numeric Functions Date and Time Functions Functions in MySQL Functions in MySQL
  • 64. Table – Emp Table – Emp Table – Emp Table – Emp Table – Emp Ecode Ename Dept City Gender Salary 1001 A. Williams Production Ahmedabad M 46000 1002 Sanjeev Batra Personnel Jalandhar M 30000 1003 Ishita Sharma RND New Delhi F 50000 1004 Suresh Baroth RND Jaipur M 55000 1005 Seema Sharma Marketing Shimla F 36500 1006 Akram Hussain Servicing Hamirpur M 20000 1007 Dhiraj Patel Production Surat M 45000 1008 Meera Kumari RND Phagwara F 40000
  • 65. String functions are being used to manipulate the text string. Some of the commonly used string function of MySQL are as follows: 1. LENGTH() : Length() function returns the length of a string i.e. Number of characters in a string including letters, spaces and anything else. Syntax : LENGTH( String | Column) String or Text Functions String or Text Functions Example: SELECT LENGTH(“Informatics Practices”); Output: 21 Q. Display the Employee Name and their length from Emp table. Sol.: SELECT Ename , LENGTH(Ename) FROM Emp; .
  • 66. 2. UCASE() / UPPER() : Ucase() / Upper() takes any String or Column name and converts any letters in it to Capital letters or uppercase. Syntax : UCASE / UPPER( String | Column name) String or Text Functions String or Text Functions Example: SELECT UCASE(“Informatics Practices”); OR SELECT UPPER(“Informatics Practices”); Output: INFORMATICS PRACTICES Q. Display all city names to upper case in Emp table. Sol.: SELECT UPPER(City) FROM Emp; .
  • 67. 3. LCASE() / LOWER() : Lcase() / Lower() takes any String or Column name and converts any letters in it to Small letters or lowercase. Syntax : LCASE / LOWER( String | Column name) String or Text Functions String or Text Functions Example: SELECT LCASE(“Informatics Practices”); OR SELECT LOWER(“Informatics Practices”); Output: informatics practices Q. Display all city names to lower case in Emp table. Sol.: SELECT LOWER(City) FROM Emp; *LOWER() does opposite to UPPER function
  • 68. 4. LEFT( ) : LEFT( ) function returns the number of characters as specified from leftmost side of the String or Column name. Syntax : LEFT( String | Column name , length) * Where length is the number of characters to be returned. String or Text Functions String or Text Functions Example: SELECT LEFT(“Informatics Practices” , 6); Output: Inform Q. Display left five characters from Ename column of the Emp table. Sol.: SELECT LEFT(Ename , 5) FROM Emp;
  • 69. 5. RIGHT( ) : RIGHT( ) function returns the number of characters as specified from rightmost side of the String or Column name. Syntax : RIGHT( String | Column name , length) * Where length is the number of characters to be returned. String or Text Functions String or Text Functions Example: SELECT RIGHT(“Informatics Practices” , 3); Output: ces Q. Display last three characters from Ename column of the Emp table. Sol.: SELECT RIGHT(Ename , 3) FROM Emp;
  • 70. 6. SUBSTR( ) / SUBSTRING() : This function returns a specified characters from string starting at character position m to n characters long. Syntax : SUBSTR | SUBSTRING( String | Column name , m , n) * Where m is the starting character position and n is the number of characters. String or Text Functions String or Text Functions Example: SELECT SUBSTR(“Informatics Practices” , 3 , 4); Output: form SELECT SUBSTR(“INFORMATION” , -6 , 3); Output: MAT Q. Display the City starting at second character and four characters. Sol.: SELECT SUBSTR(City , 2 , 4) FROM Emp;
  • 71. 7. MID( ) : MID( ) function returns a substring starting from the specified position to the specified number of characters from String or Column name. Syntax : MID( String | Column name , Start_Position , length) * Where length is the number of characters to be returned. String or Text Functions String or Text Functions Example: SELECT MID(“Informatics Practices” , 3 , 4); Output: form Q. Display first three characters extracted from Ename of Employees. Sol.: SELECT MID(Ename , 1 , 3) FROM Emp;
  • 72. 8. INSTR( ) : This function searches String1 for String2 and returns the position of the first occurrence of string. Syntax : INSTR( String1, String2) String or Text Functions String or Text Functions Example: SELECT INSTR(“Informatics Practices”, “a”); Output: 7 Q. Display the position of character ‘a’ in the Employee names. Sol.: SELECT Ename , INSTR(Ename , ‘a’) FROM Emp;
  • 73. 9. LTRIM( ) : This function removes leading spaces from a String. Syntax : LTRIM( String) Example: SELECT LTRIM(“ INFORMATION TECH”); Output: INFORMATION TECH String or Text Functions String or Text Functions 10. RTRIM( ) : This function removes trailing spaces from a String. Syntax : RTRIM( String) Example: SELECT RTRIM(“ INFORMATION TECH ”); Output: INFORMATION TECH
  • 74. 11. TRIM( ) : This function removes leading as well as trailing spaces from a String. Syntax : TRIM( String) Example: SELECT TRIM(“ INFORMATION TECH ”); Output: INFORMATION TECH String or Text Functions String or Text Functions
  • 75. Mathematical functions accept numeric input and returns numeric values. 1. POWER() / POW() : This function returns the value of x to the y power. Syntax : POWER | POW( x , y ) * Where x is the base and y is raise to the power. Numeric or Math Functions Numeric or Math Functions Example: SELECT POWER(2 , 3); Output: 8 Q. Write the power of (4.56)3. Sol.: SELECT POWER(4.56 , 3); Output: 94.818816.
  • 76. 2. ROUND() : This function rounds numbers to a given number of digits of precision. That means , returns the number rounded to n decimal places. Syntax : ROUND( Number | Column name , n) * Where n is the decimal places. Numeric or Math Functions Numeric or Math Functions Example: SELECT ROUND(12.3457 , 2); Output: 12.35 Note : It rounds the number or Column to n decimal places. If n is omitted , no decimal places. If n is negative , numbers to the left of decimal point are rounded. Example: SELECT ROUND(15.193 , -1) Output: 20
  • 77. 3. MOD() : This function returns modulus i.e. remainder of m divided by n. Syntax : MOD( m , n) * Where m is dividend and n is divisor. Numeric or Math Functions Numeric or Math Functions Example: SELECT MOD(11 , 4); Output: 3 Example: SELECT MOD(Salary , 500) FROM Emp;
  • 78. 4. TRUNCATE() : This function truncates or chops off digits of precision from a number. Syntax : TRUNCATE( Number , n) * Where n is the decimal place. It truncates the number to n decimal place. Numeric or Math Functions Numeric or Math Functions Example: SELECT TRUNCATE(16.534 , 1); Output: 16.5 Example: SELECT TRUNCATE(15.79); Output: 15 Example: SELECT TRUNCATE(15.79 , -1); Output: 10
  • 79. 1. CURDATE() : This function returns the current date. Syntax : CURDATE( ) Date Functions Date Functions Example: SELECT CURDATE(); Output: 2020 – 08 -05 2. NOW() : This function returns the current date and time. Syntax : NOW( ) Example: SELECT NOW(); Output: 2020 – 08 -05 10:37:41
  • 80. 3. DATE() : This function extracts the date part of a date time expression. Syntax : DATE( Date Time expr) Date Functions Date Functions Example: SELECT DATE(“ 2020 – 08 -05 10:37:41”); Output: 2020 – 08 -05 4. MONTH() : This function returns the month (i.e. 1 – 12) from a date passed. Syntax : MONTH(Date expr ) Example: SELECT MONTH((“ 2020 – 08 -05” ); Output: 08
  • 81. 5. MONTHNAME() : This function returns the month name from a date passed. Syntax : MONTHNAME( Date expr) Date Functions Date Functions Example: SELECT MONTHNAME(“ 2020 – 08 -05”); Output: August 6. YEAR() : This function returns the year from a date passed. Syntax : YEAR(Date expr ) Example: SELECT YEAR((“ 2020 – 08 -05” ); Output: 2020
  • 82. 7. DAY() : This function returns the Day of month (i.e. 1 – 31) from a date passed. Syntax : DAY( Date expr) Date Functions Date Functions Example: SELECT DAY(“ 2020 – 08 -05”); Output: 05 8. DAYNAME() : This function returns the Dayname from a date passed. Syntax : DAYNAME(Date expr ) Example: SELECT DAYNAME((“ 2020 – 08 -05” ); Output: Wednesday
  • 83. Unit 2 : Database Query Unit 2 : Database Query using SQL using SQL Grouping Records in MySQL
  • 84. “Group functions or Aggregate functions operate on sets of rows to give one result per group.“ That means, these function work upon groups of rows, and hence are called Multiple Row Functions. Note: All the Group functions are used in SELECT statement. Syntax: SELECT <Function Name>(<Parameter>) FROM <Table Name>; The Group functions are of following types: (1) MIN() (2) MAX() (3) SUM() (4) AVG() (5) COUNT() Group Functions or Aggregate Functions Group Functions or Aggregate Functions
  • 85. 1. MIN() : This function returns the minimum value of a given Column or expression, ignoring the null values. Syntax : MIN([DISTINCT | ALL] Column | Expr ) Group Functions or Aggregate Functions Group Functions or Aggregate Functions Example : SELECT MIN(100, 50, 400, 200); Output: 50 Q. Write a query to find the minimum salary in Emp table. Sol. SELECT MIN(Salary) FROM Emp;
  • 86. 2. MAX() : This function returns the maximun value of a given Column or expression, ignoring the null values. Syntax : MAX([DISTINCT | ALL] Column | Expr ) Group Functions or Aggregate Functions Group Functions or Aggregate Functions Example : SELECT MAX(100, 50, 400, 200); Output: 400 Q. Write a query to find the maximum salary in Emp table. Sol. SELECT MAX(Salary) FROM Emp;
  • 87. 3. SUM() : This function returns the sum of values in given Column or expression, ignoring the null values. Syntax : SUM([DISTINCT | ALL] Column | Expr ) Group Functions or Aggregate Functions Group Functions or Aggregate Functions Example : SELECT SUM(100, 50, 400, 200); Output: 750 Q. Write a query to find the Total salary of Employees in Emp table. Sol. SELECT SUM(Salary) FROM Emp;
  • 88. 4. AVG() : This function returns an average value of the numeric Column or expression, ignoring the null values. Syntax : AVG([DISTINCT | ALL] Column | Expr ) Group Functions or Aggregate Functions Group Functions or Aggregate Functions Example : SELECT AVG(100, 300, 400, 200); Output: 250 Q. Write a query to find the Average salary of Employees in Emp table. Sol. SELECT AVG(Salary) FROM Emp; Q. Write a query to find Sum and Average salary of Employees working in RND department. Sol. SELECT Sum(Salary), AVG(Salary) FROM Emp WHERE Dept = “RND”;
  • 89. 5. COUNT() : This function counts the number of rows in the table, including duplicates and those with nulls. Syntax : COUNT({ * | [DISTINCT | ALL] Expr }) Group Functions or Aggregate Functions Group Functions or Aggregate Functions (a) (b) The COUNT() function has two formats : COUNT (*) : returns the number of rows in the table, including duplicates rows containing NULL values in any column. COUNT ( Expr ) : returns the number of non NULL rows in the column identified by expr.
  • 90. Group Functions or Aggregate Functions Group Functions or Aggregate Functions Q. Q. Display number of records or rows in Emp table. Sol. SELECT COUNT(*) FROM Emp; Q. Display the number of department available in Emp table. Sol. SELECT COUNT(DISTINCT Dept) FROM Emp;
  • 91. GROUP BY clause is used with the SELECT statement to divide the rows in a table into groups. The Groups are determined by the columns that you specify in the GROUP BY clause and groups rows that have the same values. The GROUP BY clause is used with Aggregate or Group functions (MIN(), MAX() , SUM(), AVG(), COUNT()) to group the result-set by one or more columns. Note: All the Group functions treated the table as one large group of information. At times, we need to divide the table of information into groups. This can be done by using GROUP BY clause. Grouping Records : GROUP BY clause Grouping Records : GROUP BY clause Grouping Records : GROUP BY clause Grouping Records : GROUP BY clause
  • 92. Table – Emp Table – Emp Table – Emp Table – Emp Table – Emp Ecode Ename Dept City Gender Salary 1001 A. Williams Production Ahmedabad M 46000 1002 Sanjeev Batra Personnel Jalandhar M 30000 1003 Ishita Sharma RND New Delhi F 50000 1004 Suresh Baroth RND Jaipur M 55000 1005 Seema Sharma Marketing Shimla F 36500 1006 Akram Hussain Servicing Hamirpur M 20000 1007 Dhiraj Patel Production Surat M 45000 1008 Meera Kumari RND Phagwara F 40000
  • 93. Q.1. Display the total salary offered to each Department. Sol. SELECT Dept, SUM(Salary) FROM Emp GROUP BY Dept; Output: Grouping Records : GROUP BY clause Grouping Records : GROUP BY clause Grouping Records : GROUP BY clause Grouping Records : GROUP BY clause Dept SUM(Salary) Production 91000 Personnel 30000 RND 145000 Marketing 36500 Servicing 20000
  • 94. Q.2. Display the maximum and minimum Salary of Employees Department wise for RND department. Sol. SELECT Dept, MAX(Salary), MIN(Salary) FROM Emp WHERE Dept = ‘RND’ GROUP BY Dept; Output: Grouping Records : GROUP BY clause Grouping Records : GROUP BY clause Grouping Records : GROUP BY clause Grouping Records : GROUP BY clause Dept MAX(Salary) MIN(Salary) RND 55000 40000
  • 95. HAVING clause can be used to restrict groups on the basis of Aggregate or Group function. The MySQL performs the following steps when we use the HAVING clause: Rows are grouped The group function is applied to the group The groups that match the criteria in the HAVING clause are displayed Excluding Group Results : HAVING clause Excluding Group Results : HAVING clause Excluding Group Results : HAVING clause Excluding Group Results : HAVING clause Q. Display the average salary of Employees Department wise, whose average salary more than 30000 Sol. SELECT Dept, AVG(Salary) FROM Emp GROUP BY Dept HAVING AVG(Salary) > 30000;
  • 96. Illegal Queries with GROUP BY Clause Q. Display the average salary of Employees Department wise, whose average salary more than 30000 Sol. SELECT Dept, AVG(Salary) FROM Emp WHERE AVG(Salary) >30000 GROUP BY Dept; Output: ERROR 1111 Q. Display the Total salary of Employees Department wise and display only those rows having Total salary more than 60000. Excluding Group Results : HAVING clause Excluding Group Results : HAVING clause Excluding Group Results : HAVING clause Excluding Group Results : HAVING clause
  • 97. Please send your feedback to arvindsingh. dav@gmail.com Whatsapp : 98358 11914 Thanks Thanks