0% found this document useful (0 votes)
34 views

Database Overview

DatabaseOverview

Uploaded by

babjeereddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Database Overview

DatabaseOverview

Uploaded by

babjeereddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 101

Database Overview

S511 Session 2, IU-SLIS 1


Outline
• Database
– What, Why, How
• Evolution of Database
– File System
– Data Models
• Hierarchical
• Network
• Relational
• Entity-Relationship
• Object-Oriented
– Web Database

2
Database: What
• Database
– is collection of related data and its metadata organized in a structured format
– for optimized information management

• Database Management System (DBMS)


– is a software that enables easy creation, access, and modification of databases
– for efficient and effective database management

3
Database Management System
- manages interaction between end users and database

Database Systems: Design, Implementation, & Management: Rob & Coronel

4
Database System Environment

 Hardware
 Software
- OS
- DBMS
- Applications

 People
 Procedures
 Data

Database Systems: Design, Implementation, & Management: Rob & Coronel

5
Database: Why
• Purpose of Database
– Optimizes data management
– Transforms data into information

• Functions of DBMS/Database System


– Stores data and related data entry forms, report definitions, etc.
– Hides the complexities of relational database model from the user
• facilitates the construction/definition of data elements and their relationships
• enables data transformation and presentation

– Enforces data integrity


– Implements data security management
• access, privacy, backup & restoration
Database: Data Models
• Importance
– Abstraction of complex real-word data structures in relative simple (graphical)
representations
– Facilitate interaction among the designer, the applications programmer, and
the end user

• Basic Building Blocks


– Entity
• thing about which data are to be collected and stored
– Attribute
• a characteristic of an entity
– Relationship
• describes an association among entities
– Constraint
• restrictions placed on the data

7
Evolution of Data Models
• Timeline

1960s 1970s 1980s 1990s 2000+

File-based

Hierarchical
Object-oriented
Network

Relational Web-based
Entity-Relationship

8
Database: Historical Roots
• Manual File System
– to keep track of data
– used tagged file folders in a filing cabinet
– organized according to expected use
• e.g. file per customer
– easy to create, but hard to
• locate data
• aggregate/summarize data

• Computerized File System


– to accommodate the data growth and information need
– manual file system structures were duplicated in the computer
– Data Processing (DP) specialists wrote customized programs to
• write, delete, update data (i.e. management)
• extract and present data in various formats (i.e. report)

9
File System: Example

Database Systems: Design, Implementation, & Management: Rob & Coronel

10
File System: Weakness
• Weakness
– “Islands of data” in scattered file systems.

• Problems
– Duplication
• same data may be stored in multiple files
– Inconsistency
• same data may be stored by different names in different format
– Rigidity
• requires customized programming to implement any changes
• cannot do ad-hoc queries

• Implications
– Waste of space
– Data inaccuracies
– High overhead of data manipulation and maintenance

11
Database System vs. File System

Database Systems: Design, Implementation, & Management: Rob & Coronel

12
File System: Problem Case
CUSTOMER file AGENT file SALES file

A_Name (15 char) A_Name (20 char) AGENT (20 char)

Carol Johnson Carol T. Johnson Carol J. Smith

- inconsistent field name, field size


- inconsistent data values
- data duplication

13
Hierarchical Database
• Background
– Developed to manage large amount of data for complex manufacturing
projects
– e.g., Information Management System (IMS)
• IBM-Rockwell joint venture
• clustered related data together
• hierarchically associated data clusters using pointers

• Hierarchical Database Model


– Assumes data relationships are hierarchical
• One-to-Many (1:M) relationships
– Each parent can have many children
– Each child has only one parent
– Logically represented by an upside down tree

14
Hierarchical Database: Example

Database Systems: Design, Implementation, & Management: Rob & Coronel

15
Hierarchical Database: Pros & Cons
• Advantages
– Conceptual simplicity
• groups of data could be related to each other
• related data could be viewed together
– Centralization of data
• reduced redundancy and promoted consistency

• Disadvantages
– Limited representation of data relationships
• did not allow Many-to-Many (M:N) relations
– Complex implementation
• required in-depth knowledge of physical data storage
– Structural Dependence
• data access requires physical storage path
– Lack of Standards
• limited portability

16
Network Database
• Objectives
– Represent more complex data relationships
– Improve database performance
– Impose a database standard

• Network Database Model


– Similar to Hierarchical Model
• Records linked by pointers
– Composed of sets
• Each set consists of owner (parent) and member (child)
– Many-to-Many (M:N) relationships representation
• Each owner can have multiple members (1:M)
• A member may have several owners

17
Network Database: Example

Database Systems: Design, Implementation, & Management: Rob & Coronel

18
Network Database: Pros & Cons
• Advantages
– More data relationship types
– More efficient and flexible data access
• “network” vs. “tree” path traversal
– Conformance to standards
• enhanced database administration and portability

• Disadvantages
– System complexity
• require familiarity with the internal structure for data access
– Lack of structural independence
• small structural changes require significant program changes

19
Relational Database
• Problems with legacy database systems
– Required excessive effort to maintain
• Data manipulation (programs) too dependent on physical file structure
– Hard to manipulate by end-users
• No capacity for ad-hoc query (must rely on DB programmers).

• Evolution in Data Organization

– E. F. Codd’s Relational Model proposal


• Separated the notion of physical representation (machine-view)
from logical representation (human-view)
• Considered ingenious but computationally impractical in 1970

– Relational Database Model


• Dominant database model of today
• Eliminated pointers and used tables to represent data
• Tables
– flexible logical structure for data representation
– a series of row/column intersections
– related by sharing common entity characteristic(s)

20
Relational Database: Example
 Provides a logical “human-level” view of the data and associations
among groups of data (i.e., tables)

Customer_ID Customer_Account Agent_ID


1224 4556 23
1225 4558 25

Agent_ID Last_Name First_Name Phone


23 Sturm David 334-5678
25 Long Kyle 556-3421

Customer_ID Last_Name First_Name Phone Account_Balance


1224 Vira Dyne 678-9987 1223.95
1225 Davies Tricia 556-3342 234.25

21
Relational Database: Pros & Cons
• Advantages
– Structural independence
• Separation of database design and physical data storage/access
• Easier database design, implementation, management, and use
– Ad hoc query capability with Structured Query Language (SQL)
• SQL translates user queries to codes

• Disadvantages
– Substantial hardware and system software overhead
• more complex system
– Poor design and implementation is made easy
• ease-of-use allows careless use of RDBMS

22
Normalization:
Normalization is a technique which is used to organize the data in the database. It is a systematic
approach to remove the data redundancy.

There are following Four Normal Forms used in Database Normalization:


1.First Normal Form
2.Second Normal Form
3.Third Normal Form
4. Boyce-code Normal Form(BCNF)

First Normal Form/1st Normal Form:


The first normal form is the normal form of database where data must not contain repeating groups.

1.It contains only automic values.

23
Example

24
Second Normal Form/2nd Normal Form:
1.It is in First normal form

2.There should not be any partial dependency of any column on primary key.

3.All Non-key attributes are fully functionally dependent on primary.

Here We will see that there is composite key as{ Employee No,Department
No}.Employee No is dependent on Employee Name and Department is dependent on
Department No.We can split the above table into 2 different tables:

25
26
Third Normal Form/3rd Normal Form:
The database is in Third normal form if it satisfies following conditions:

1.It is in Second normal form

2.There is no transitive functional dependency

Transitive functional dependency

Consider a relation R(ABC), where A, B and C are the attributes of the relation R.
A Transitive dependency exists when you have the following functional
dependency pattern,A→B and B→C; therefore, A→C.

27
Book→Author: Here, the Book attribute determines the Author attribute. If you know
the book's name, you can learn the author's name.

Author→Author_Nationality: If we know the Author name then we can


determine Author_Nationality as well.

Book→Author_Nationality: If we know the book name, we can determine


the AuthorsNationality via the Author column.

28
S511 Session 2, IU-SLIS 29
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986,
and of the International Organization for Standardization (ISO) in 1987

What Can SQL do?


SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views

30
Types of SQL Commands
categories of commands used in SQL to perform various functions

The main categories are


DDL (Data Definition Language)
DML (Data Manipulation Language)
DQL (Data Query Language)
DCL (Data Control Language)
Transactional control commands
DDL
DDL is short name of Data Definition Language, which deals with database schemas and
descriptions, of how the data should reside in the database.

Create - to create a database and its objects like (table, index, views, store procedure)
ALTER - alters the structure of the existing database
DROP - delete objects from the database
TRUNCATE - remove all records from a table
COMMENT - add comments to the data dictionary
31
RENAME - rename an object
Oracle Datatypes
Fixed-length character data of length size bytes or Fixed for every row in the table (with trailing blanks);
Char characters maximum size is 2000 bytes per row

VARCHAR2 Variable-length character data Variable for each row, up to 4000 bytes per row

NCHAR Fixed-length Unicode character 2000 bytes per row

NVARCHAR2 Variable-length Unicode character data The upper limit is 4000 bytes per row

CLOB Single-byte character data Up to 232 - 1 bytes, or 4 gigabytes.

NCLOB Unicode national character set (NCHAR) data. Up to 232 - 1 bytes, or 4 gigabytes.

LONG Variable-length character data 2 gigabytes

S511 Session 2, IU-SLIS 32


Oracle Datatypes

NUMBER (p, s) Variable-length numeric dataVariable-length numeric The maximum space required for a
data. Maximum precision p and/or scale s is 38. given column is 21 bytes per row

DATE Fixed-length date and time data Fixed at 7 bytes for each row

INTERVAL YEAR A period of time, represented as years and months. Fixed at 5 bytes.
(precision) TO
MONTH

INTERVAL DAY A period of time, represented as days, hours, Fixed at 11 bytes.


(precision) TO minutes, and seconds.
SECOND (precision)
BLOB Unstructured binary data 4 gigabytes

BFILE Binary data stored in an external file 4 gigabytes

S511 Session 2, IU-SLIS 33


Create Database Command

create database if not exists test

SQL CREATE TABLE Example

create table Employees(


Employee_id int,
Last_name varchar(40),
First_name varchar(40),
Address varchar(40),
City varchar(40))

Insert into Employees values(1,'Babjee','Reddy','Tambaram','Chennai');

Insert into Employees values(2,'Naveen','Reddy','Tambaram','Chennai');

Insert into Employees(Employee_id,Last_name,City) values(3,'Ram','Bangalure');

34
Creating Table With Existing Table

Create Table Employees_Back as select * from Employees;

Create Table Employees_Back1 As Select Employee_id,First_name,Last_name From


Employees;

Create Table Employees_Back2 As Select Employee_id,First_name,Last_name From


Employees where Employee_id >100;

Creating Table With Auto Increment

CREATE TABLE EMPLOYEES1( EMPLOYEE_ID INT NOT NULL auto_increment PRIMARY KEY,
LAST_NAME VARCHAR(40),
FIRST_NAME varchar(40),
SALARY decimal(10,2),
DOB DATE)
Insert Into Employees1(first_name,last_name,salary,dob) values('Babjee','Reddy',3000,'2004-
10-20')

35
Create Table with Default value

CREATE TABLE Employees_default (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int,
City varchar(255) DEFAULT 'Chennai‘
);

Insert Into Employees_Default(Id,LastName,FirstName,Age) values(1,'Babjee','Reddy',35);

Insert Into Employees_Default values(1,'Babjee','Reddy',35,'Hyderabad');

CREATE TABLE Employees_default1 (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
Dob datetime default CURRENT_TIMESTAMP()
);

Insert Into Employees_default1(Id,FirstName,LastName,city) values (1,'Babjee','Reddy','Hyderabad'); 36


Temporary Tables
A TEMPORARY table is visible only within the current session, and is dropped automatically
when the session is closed.

CREATE temporary TABLE DUMMY(ID INT,NAME varchar(40));


INSERT INTO DUMMY VALUES(1,'BABJEE');

Constraints
SQL constraints are used to specify rules for the data in a table.

Constraints can be column level or table level. Column level constraints apply to a column,
and table level constraints apply to the whole table

The following constraints are commonly used in SQL:

NOT NULL - Ensures that a column cannot have a NULL value


UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
FOREIGN KEY - Uniquely identifies a row/record in another table
CHECK - Ensures that all values in a column satisfies a specific condition
ENUM is a string object with a value chosen from a list of permitted values.
SET can have zero or more values. Each of the values must be chosen from a list of permitted values.

37
Not Null Constraint

Create Table Employees_NotNull


(Id int Not null,
Employee_Name varchar(40) Not Null,
Salary decimal(10,2)
)

Insert Into Employees_NotNull Values(null,'Babjee',3000);Insert


Into Employees_NotNull Values(1,null,3000);
Insert Into Employees_NotNull Values(1,'Babjee',3000);

38
Primary Key
Create Table Employees_PK(
Id int Primary Key,
Employee_Name varchar(40),
Salary decimal
);
Insert into Employees_PK Values(1,'Babjee',30000);
Insert into Employees_PK Values(1,'Babjee',30000);
Insert into Employees_PK Values(null,'Babjee',30000);

Create Table Employees_PK1(


Id int,
Employee_Name varchar(40),
Salary decimal ,
constraint emp_k primary key(id)
);

39
Create Table Employees_PK2(
Id int,
Employee_Name varchar(40),
Salary decimal ,
constraint emp_k primary key(id,Employee_name)
);
Insert into Employees_PK2 Values(1,'Babjee',30000);Insert
into Employees_PK2 Values(1,'Babjee',30000);
Insert into Employees_PK2 Values(1,'Naveen',30000);

select *from information_schema.table_constraints


where table_name ='Employees_pk2'

40
Unique Constraint

Create Table Employees_Unique(


id int unique ,
Employee_Name Varchar(40),
Salary decimal(10,2)
)
Insert into Employees_Unique values(1,'Naveen',50000); Insert into
Employees_Unique values(1,'Naveen',50000); Insert into Employees_Unique
values(NUll,'Ram',50000);

Create Table Employees_Unique1(


id int unique ,
Employee_Name Varchar(40) Unique,
Salary decimal(10,2)
)

Create Table Employees_Unique2(


id int ,
Employee_Name Varchar(40) ,
Salary decimal(10,2),
constraint emp_uqniq Unique(id,Employee_name)
41
)
Check Constraint
Create Table Employees_Check(
id int ,
Employee_Name Varchar(40) ,
Salary decimal(10,2),
constraint emp_cheq check(salay >50000)
);

insert into employees_check values(1,'Sham',3000

select * from employees_check

42
Foreign Key
Create table Supplier(
Supplier_id int Primary key,
Supplier_name varchar(40)
);
Insert Into Supplier value(1,'Abc Company');
Insert Into Supplier value(2,'Bca Company');

Create Table Products(


Product_id int,
Product_name varchar(40),
Supplier_id int ,
foreign key(supplier_id) references supplier(supplier_id)
);
Insert Into Products values(1,'Pen',1);
Insert Into Products values(2,'Pencil',3);

Create Table Products(


Product_id int,
Product_name varchar(40),
Supplier_id int ,
foreign key(supplier_id) references supplier(supplier_id) on delete cascade
43
);
ENMU
ENUM is a string object with a value chosen from a list of permitted values that are
enumerated explicitly in the column specification at table creation time

CREATE TABLE shirts (


name VARCHAR(40),
size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);

INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'), ('polo
shirt','small');

SET
A SET is a string object that can have zero or more values, each of which must be chosen from
a list of permitted values specified when the table is created

CREATE TABLE myset (col SET('a', 'b', 'c', 'd'));

INSERT INTO myset (col) VALUES -> ('a,d'), ('d,a'), ('a,d,a'), ('a,d,d'), ('d,a,d');

INSERT INTO myset (col) VALUES ('a,d,d,s');


Show wanrnings 44
Alter Command

Changing data type


Alter table Employees modify employee_id float;

Channing form Null to Not Null /Not Null to Null


Alter table Employees modify employee_id float Not null;

Increasing Column Length


Alter table Employees modify Last_name varchar(300);

Adding Column
Alter table Employees add pincode int;

Adding Column multiple columns


Alter table Employees add (address1 varchar(40),address2 varchar(40))in;

Dropping column
Alter table Employees drop column address2

Rename Table
alter table employees1 rename to employee_new1
45
Rename Column
Alter table employees CHANGE city new_city varchar(40);

Adding Constraints

alter table employees add constraint emp_pk primary key(employee_id);

alter table employees drop primary key

alter table employees add constraint emp_uk UNIQUE(last_name);

ALTER TABLE EMPLOYEES DROP index emp_uk

ALTER TABLE products drop foreign key products_ibfk_1

46
Drop Command

Drop table test;

Truncate table Command

Truncate Myset1

47
DML Commands

INSERT – insert data into a table.


UPDATE – updates existing data within a table.
SELECT – retrieve data from the a database.
DELETE – deletes all records from a table, the space for the records remain.
MERGE – UPSERT operation (insert or update)

Create Table Students(


Student_id int,
Student_name varchar(40),
Age int,
Gender varchar(6)
);

Insert into students values (1,’Susil’,22,’Male’);

Insert into students values(2,’Ram’,21’,’Male’),(3,’Sheetal’,21,’Femaile’);

Insert into students1 select * from students;

48
Update command

update students set age =35 where student_id=2

update students set student_name='Ram Kumar', age=35 where student_id=3

update students set age =25 ;

update students set age=age+5 where student_id >1;

Update students set age =null where student_id=1;

49
SELECT STATE MENT
select * from emp;

select count(*) from emp;

Comarision Operator

select empno,ename,job from emp;

select * from emp where job='CLERK';

select * from emp where deptno=20;

select * from emp where deptno !=20;

select * from emp where deptno <>20;

select * from emp where deptno >20;

select * from emp where deptno >=20;

select * from emp where deptno <20;

select * from emp where deptno <=20; 50


select * from emp where deptno between 20 and 30;

select * from emp where deptno not between 20 and 30;

select * from emp where deptno in(10,20);

select * from emp where deptno not in(10,20);

select * from emp where comm is null;

select * from emp where comm is not null;

select * from emp where ename like 'S%';

select * from emp where ename like '%S‘

select * from emp where ename not like '%S‘

select * from emp where ename like '_mith';

51
Logical Operators

select * from emp where deptno=10 and sal >4000;

select * from emp where deptno=10 or sal >4000;

select * from emp where (deptno=10 and sal >4000) or (deptno=20 and sal <4000)

Order By class

select * from emp order by ename ;

select * from emp order by ename desc;

select * from emp order by deptno,sal desc

52
Functions
MySQL has many built-in functions.

Mysql contains string, numeric, date, and some advanced functions in MySQL.

Single row function: function execute for each row

Group function: function execute group of rows

String functions

ASCII Returns the ASCII value for the specific character


select ascii('A')

CHAR_LENGTH Returns the length of a string (in characters)


select ename,char_length(ename) from emp

BIN(N) Returns a string representation of the binary value of N


SELECT BIN(12);

CHARACTER_LENGTH Returns the length of a string (in characters)


select ename,CHARACTER_LENGTH(ename) from emp 53
CONCAT Adds two or more expressions together
SELECT CONCAT("SQL ", "Tutorial ", "is ", "fun!") AS ConcatenatedString;

FIELD Returns the index position of a value in a list of values


SELECT FIELD("q", "s", "q", "l") as position;

FORMAT Formats a number to a format like "#,###,###.##", rounded to a specified


number of decimal places
SELECT FORMAT(250500.5634, 2);

INSERT Inserts a string within a string at the specified position and for a certain number
of characters
SELECT INSERT("Bigems.com", 1, 6, "Example");

INSTR Returns the position of the first occurrence of a string in another string
select instr('Babjee Reddy ponnam',' ')

LCASE Converts a string to lower-case


select lcase(ename),ename from emp

UPPER Converts a string to upper-case


select upper(ename),ename from emp
select ucase(ename),ename from emp 54
Initial captical
select CONCAT(UCASE(LEFT(ename, 1)),SUBSTRING(lower(ename), 2)) from emp;

LEFT Extracts a number of characters from a string (starting from left)


SELECT LEFT("SQL Tutorial", 3) AS ExtractString;

RIGHT Extracts a number of characters from a string (starting from left)


select right("SQL Tutorial", 8) AS ExtractString;

LENGTH Returns the length of a string (in bytes)


select length('babjee');

LPAD Left-pads a string with another string, to a certain length


select lpad('babjee',15,'*')

RPAD Right-pads a string with another string, to a certain length


select rpad('babjee',15,'*');

LTRIM Removes leading spaces from a string


SELECT LTRIM(" SQL Tutorial") AS LeftTrimmedString;

RTRIM Removes trailing spaces from a string


SELECT RTRIM("SQL Tutorial ") AS LeftTrimmedString;
55
REPEAT Repeats a string as many times as specified
select repeat("babjee ",3)

REPLACE Replaces all occurrences of a substring within a string, with a new substring
SELECT REPLACE("SQL Tutorial", "SQL", "HTML");

STRCMP Compares two strings


SELECT STRCMP("SQL Tutorial", "SQL Tutorial");

SUBSTRING Extracts a substring from a string (starting at any position)


SELECT SUBSTRING("SQL Tutorial", 5, 3) AS ExtractString;

56
Number functions

ABS Returns the absolute value of a number


select abs(-2)

CEIL Returns the smallest integer value that is >= to a number


SELECT CEIL(25.15);

COS Returns the cosine of a number


Select cos(2)

DIV Used for integer division


SELECT 10 DIV 5;

EXP Returns e raised to the power of a specified number


select exp(4)

FLOOR Returns the largest integer value that is <= to a number


SELECT FLOOR(25.75);

GREATEST Returns the greatest value of the list of arguments


select greatest(1,50,30,60)
57
LEAST Returns the smallest value of the list of arguments
select least(1,50,30,60)

LN Returns the natural logarithm of a number


select ln(2)

MOD Returns the remainder of a number divided by another number


select mod(10,2)

PI Returns the value of PI


select pi();

POW Returns the value of a number raised to the power of another number
select pow(10,2)

ROUND Rounds a number to a specified number of decimal places


select round(10.51,0)

SQRT Returns the square of a number


SELECT SQRT(64);

58
Date Function

CURDATE Returns the current date


select curdate()

CURRENT_DATE Returns the current date


select CURRENT_DATE

CURRENT_TIME Returns the current time


select current_time()

CURTIME Returns the current time


select curtime()

CURRENT_TIMESTAMP Returns the current date and time


select current_timestamp()

ADDDATE Adds a time/date interval to a date and then returns the date
select ADDDATE("2015-10-01",interval 10 DAY)
SELECT ADDDATE(curdate(),interval 10 DAY)

DATEDIFF Returns the number of days between two date values


SELECT DATEDIFF("2017-06-25", "2017-06-15"); 59
DATE_FORMAT Formats a date
SELECT DATE_FORMAT("2017-06-15", "%Y");

%a Three-characters abbreviated weekday name e.g., Mon, Tue, Wed, etc.


%b Three-characters abbreviated month name e.g., Jan, Feb, Mar, etc.
%c Month in numeric e.g., 1, 2, 3…12
%D Day of the month with English suffix e.g., 0th, 1st, 2nd, etc.
%d Day of the month with leading zero if it is 1 number e.g., 00, 01,02, …31
%e Day of the month without leading zero e.g., 1,2,…31
%f Microseconds in the range of 000000..999999
%H Hour in 24-hour format with leading zero e.g., 00..23
%h Hour in 12-hour format with leading zero e.g., 01, 02…12
%I Same as %h
%i Minutes with leading zero e.g., 00, 01,…59
%j Day of year with leading zero e.g., 001,002,…366
%k Hour in 24-hour format without leading zero e.g., 0,1,2…23
%l Hour in 12-hour format without leading zero e.g., 1,2…12
%M Full month name e.g., January, February,…December
%m Month name with leading zero e.g., 00,01,02,…12
%p AM or PM, depending on other time specifiers

60
%r Time in 12-hour format hh:mm:ss AM or PM
%S Seconds with leading zero 00,01,…59
%T Time in 24-hour format hh:mm:ss
%U Week number with leading zero when the first day of week is Sunday e.g., 00,01,02…53
%u Week number with leading zero when the first day of week is Monday e.g., 00,01,02…53

The following are some commonly used date format strings:

DATE_FORMAT string Formatted date


%Y-%m-%d 2018/4/25
%e/%c/%Y 4/7/2013
%c/%e/%Y 7/4/2013
%d/%m/%Y 4/7/2013
%m/%d/%Y 7/4/201

61
DATE_SUB Subtracts a time/date interval from a date and then returns the date
SELECT DATE_SUB("2017-06-15", INTERVAL 10 DAY);

DAY Returns the day of the month for a given date


SELECT DAY("2017-06-15");

DAYNAME Returns the weekday name for a given date


SELECT DAYname("2017-06-15");

DAYOFMONTH Returns the day of the month for a given date


SELECT dayofmonth("2017-06-15");

DAYOFWEEK Returns the weekday index for a given date


SELECT dayofweek("2017-06-15");

DAYOFYEAR Returns the day of the year for a given date


SELECT dayofyear(curdate());

EXTRACT Extracts a part from a given date


SELECT extract(year from curdate())

SELECT extract(month from curdate())


62
SELECT extract(day from curdate())

SELECT extract(week from curdate())

HOUR Returns the hour part for a given date


select hour(current_time())

LAST_DAY Extracts the last day of the month for a given date
select last_day(current_time())

LOCALTIME Returns the current date and time


select localtime()

LOCALTIMESTAMP Returns the current date and time


select localtimestamp()

MINUTE Returns the minute part of a time/datetime


select minute(localtime())

MONTH Returns the month part for a given date


select month(localtime())
63
MONTHNAME Returns the name of the month for a given date
select monthname(localtime())

NOW Returns the current date and time


select now()

QUARTER Returns the quarter of the year for a given date value
select quarter(now())

WEEK Returns the week number for a given date


SELECT WEEK("2017-06-15");

WEEKDAY Returns the weekday number for a given date

WEEKOFYEAR Returns the week number for a given date


SELECT WEEKOFYEAR("2017-06-15");

YEAR Returns the year part for a given date


select year(now())

64
MySQL Advanced Functions

BIN Returns a binary representation of a number


select bin(10)

CASE Goes through conditions and return a value when the first condition is met
select empno,ename,sal,deptno,
case when deptno =10 then "Accounts"
when deptno =20 then "IT"
else "Admin"
end
from emp

CAST Converts a value (of any type) into a specified datatype


SELECT CAST("2017-08-29" AS DATE);

SELECT CAST("14:06:10" AS TIME);

select cast(1234 as char(4));

select cast( "123" as signed);

65
COALESCE Returns the first non-null value in a list
SELECT COALESCE(NULL, NULL, NULL, 'Biges.com', NULL, 'Example.com');

CURRENT_USER Returns the user name and host name for the MySQL account that the
server used to authenticate the current client
select current_user()

DATABASE Returns the name of the current database


select database()

IF Returns a value if a condition is TRUE, or another value if a condition is FALSE

SELECT IF(500<1000, "YES", "NO");

ISNULL Returns 1 or 0 depending on whether an expression is NULL


select isnull(comm) ,comm from emp

NULLIF Compares two expressions and returns NULL if they are equal. Otherwise, the first
expression is returned
select nullif(ename,'smith') from emp

66
Ifnull
select ifnull(comm,0),comm from emp

SESSION_USER Returns the current MySQL user name and host name
select session_user()

SYSTEM_USER Returns the current MySQL user name and host name
select system_user()

USER Returns the current MySQL user name and host name
select user()

VERSION Returns the current version of the MySQL database


select version()

67
GROUP FUNCTIONS

SELECT DEPTNO,
MAX(SAL) AS MAX_SAL,
MIN(SAL) AS MIN_SAL,
AVG(SAL) AS AVG_SAL,
SUM(SAL) AS SUM_SAL,
COUNT(SAL) AS NO_OF_EMP
FROM EMP
GROUP BY DEPTNO

SELECT JOB,DEPTNO,
MAX(SAL) AS MAX_SAL,
MIN(SAL) AS MIN_SAL,
AVG(SAL) AS AVG_SAL,
SUM(SAL) AS SUM_SAL,
COUNT(SAL) AS NO_OF_EMP
FROM EMP
GROUP BY DEPTNO,JOB

68
WITH ROLLOUP

SELECT DEPTNO,
SUM(SAL) AS SUM_SAL
FROM EMP
GROUP BY DEPTNO WITH ROLLUP

SELECT
JOB,DEPTNO,
SUM(SAL) AS SUM_SAL
FROM EMP
GROUP BY DEPTNO,JOB
WITH ROLLUP

SELECT
if(grouping(deptno),"Alldeptno",deptno) as deptno,
if(grouping(job),"All jobs",job) as jobs ,
SUM(SAL) AS SUM_SAL
FROM EMP
GROUP BY DEPTNO,job WITH ROLLUP

69
HAVING CLASS

SELECT
DEPTNO,
MAX(SAL) AS MAX_SAL,
MIN(SAL) AS MIN_SAL,
AVG(SAL) AS AVG_SAL,
SUM(SAL) AS SUM_SAL,
COUNT(SAL) AS NO_OF_EMP
FROM EMP
GROUP BY DEPTNO
HAVING COUNT(SAL) >4

70
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them

(INNER) JOIN: Returns records that have matching values in both tables

LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from
the right table

RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records
from the left table

FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

CROSS JOIN

NATURAL JOIN

SELF JOIN

NO EQUIE JOIN 71
SQL EQUI JOIN performs a JOIN against equality or matching column(s) values of
the associated tables
SELECT
EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
EMP.DEPTNO,
DNAME
FROM EMP,DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO
INNER JOIN
EMP.DEPTNO=DEPT.DEPTNO

72
SELECT
EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
EMP.DEPTNO,
DNAME
FROM EMP
INNER JOIN DEPT
ON EMP.DEPTNO=DEPT.DEPTNO

73
INNER JOIN WITH ALIES
SELECT
EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
E.DEPTNO,
DNAME
FROM EMP E
INNER JOIN DEPT D
ON E.DEPTNO=D.DEPTNO

SELECT
EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
E.DEPTNO,
DNAME
FROM EMP E
74
JOIN DEPT D ON E.DEPTNO=D.DEPTNO
RIGHT OUTER JOIN

SELECT
EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
D.DEPTNO,
DNAME
FROM EMP E
RIGHT JOIN DEPT D
ON E.DEPTNO=D.DEPTNO

75
LEFT OUTER JOIN

SELECT
EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
E.DEPTNO,
DNAME
FROM EMP E
LEFT JOIN DEPT D
ON E.DEPTNO=D.DEPTNO

76
FULL OUTER JOIN
SELECT
EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
E.DEPTNO,
DNAME
FROM EMP E
FULL JOIN DEPT D
ON E.DEPTNO=D.DEPTNO

NATURAL JOIN
SELECT
EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
DEPTNO,
DNAME
FROM EMP NATURAL JOIN DEPT

77
SELF JOIN
SELECT
E.EMPNO,
E.ENAME,
E.JOB,
E.MGR,
M.ENAME AS MANAGER
FROM EMP E, EMP MWHERE E.MGR =M.EMPNO

NO EQUI JOIN

SELECT
EMPNO,
ENAME,
SAL,
GRADE
FROM
EMP E, SALGRADE S
WHERE E.SAL BETWEEN S.LOSAL AND S.HISAL

SELECT
DNAME,
MAX(SAL) AS MAX_SAL,
MIN(SAL) AS MIN_SAL,
AVG(SAL) AS AVG_SAL,
SUM(SAL) AS SUM_SAL,
COUNT(SAL) AS NO_OF_EMP
FROM EMP ,DEPT
WHERE EMP.DEPTNO =DEPT.DEPTNO
GROUP BY DNAME;
78
SET OPERATORS

SELECT * FROM FURITS


UNION
SELECT * FROM FRUITS1

SELECT * FROM FURITS


UNION ALL
SELECT * FROM FRUITS1

COMMON FRUITS FROM BOTH TABLE

SELECT * FROM FRUITS WHERE EXISTS(SELECT * FROM FRUITS1 WHERE


FRUITS.FRUIT_NAME=FRUITS1.FRUIT_NAME);

FRUITS EXIST IN FRUIT TABLE NOT EXIST IN FRUITS1 TABLE

SELECT * FROM FRUITS WHERE NOT EXISTS(SELECT * FROM FRUITS1 WHERE


FRUITS.FRUIT_NAME=FRUITS1.FRUIT_NAME);

79
SUB QUERY

A subquery is a SQL query nested inside a larger query.

SELECT * FROM EMP WHERE SAL > (SELECT SAL FROM EMP WHERE ENAME='SMITH')

SELECT * FROM DEPT WHERE DEPTNO IN (SELECT DEPTNO FROM EMP)

SELECT * FROM DEPT WHERE DEPTNO NOT IN (SELECT DEPTNO FROM EMP)

SELECT DEPTNO, AVG(SAL) AS AVG_SAL FROM EMP GROUP BY DEPTNO HAVING AVG(SAL)
>= ALL(SELECT AVG(SAL) FROM EMP GROUP BY DEPTNO)

SELECT DEPTNO, AVG(SAL) AS AVG_SAL FROM EMP GROUP BY DEPTNO HAVING AVG(SAL)
>= ANY(SELECT AVG(SAL) FROM EMP GROUP BY DEPTNO)

SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP E WHERE SAL >(SELECT AVG(SAL) FROM


EMP I WHERE DEPTNO=E.DEPTNO) ORDER BY DEPTNO;

SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP E WHERE SAL >=(SELECT max(SAL) FROM


EMP I WHERE DEPTNO=E.DEPTNO) ORDER BY DEPTNO;

80
SELECT * FROM EMP WHERE EXISTS (SELECT DEPTNO FROM DEPT WHERE DEPTNO =EMP.DEPTNO)

SELECT * FROM DEPT WHERE NOT EXISTS (SELECT DEPTNO FROM EMP WHERE DEPTNO =DEPT.DEPTNO)

SECOND HIGHYEST SALARY

SELECT EMPNO, Sal FROM Emp e WHERE 2=(SELECT COUNT(DISTINCT Sal) FROM Emp p WHERE e.SaL<=p.Sal)

VIEWS

create view emp_dept


as select
empno,
ename,
job,
mgr,
hiredate,
sal,
comm,
emp.deptno,
dname,
location
from emp , dept
where emp.deptno =dept.deptno

81
create view emp_view1
as select
empno,
ename,
job,
mgr,
hiredate,
sal
from emp;

create view emp_view2


as select
empno,
ename,
job,
mgr,
hiredate,
sal
from emp
where deptno in (10,20);

82
create view emp_view3
as select
empno as employee_no,
ename as employee_name,
job employee_job,
mgr as manager,
hiredate,
sal
from emp ;

create view emp_view4


as select dname,
max(sal) as max_sal,

min(sal) as min_sal,
avg(sal) as avg_sal,
sum(sal) as sum_sal,
count(sal) as employee_count
from emp,dept
where emp.deptno =dept.deptno;

83
Commit/rollback

SET autocommit=0;
START TRANSACTION;
insert into dept values (60,'prod','Chennai');
select * from dept;rollback ;

Savepoint

START TRANSACTION;
savepoint a;
insert into dept values (60,'prod','Chennai');
savepoint b;
update dept set dname ='abc' where deptno=10;
select * from dept;
rollback to savepoint b;

List user in mysql

select user from mysql.user

84
GRANT AND REVOKE

grant select,update,delete on emp to root@localhost

show grants for root@localhost

revoke select,update,delete on emp from root@localhost

85
Procedures

delimiter //

create PROCEDURE getemp()


BEGIN
select * from emp;
END//
delimiter ;

Procedure with input paratmeter

CREATE PROCEDURE getdept(pdeptno int)


BEGIN
select * from emp where deptno=pdeptno;
END

86
Stored procedure with input and output parameter

CREATE PROCEDURE empsp


( IN pdeptno int, OUT total INT)
BEGIN
SELECT count(empno) INTO total FROM emp WHERE
deptno = pdeptno;
END

Procedure with local variable declaration

CREATE PROCEDURE test()


begin
DECLARE total_emp INT DEFAULT 0;
SELECT COUNT(*) INTO total_empFROM emp;
select total_emp;
end

87
Inout parameter

CREATE PROCEDURE set_counter


(INOUT count INT(4),IN inc INT(4))
BEGIN
SET count = count + inc;
END

calling inout parameter

SET @counter = 1;
CALL set_counter(@counter,1);
CALL set_counter(@counter,1);
CALL set_counter(@counter,5);
SELECT @counter;

88
Procedure with if condition

delimiter $$

CREATE PROCEDURE
updateempsal(in p_empno int(11), out p_saltype varchar(20))
BEGIN
DECLARE salary double;
SELECT sal INTO salary FROM emp WHERE empno = p_empno;
IF salary > 4000 THEN
SET p_saltype = 'Good';
ELSEIF salary > 3000 THEN
SET p_saltype = 'Fair';
else
SET p_saltype = 'Poor';
END IF;
END$$

89
Case statement

delimiter $$
CREATE PROCEDURE
empcase( in p_empno int(11), out p_saltype varchar(20))
BEGIN
DECLARE salary double;
SELECT sal INTO salary FROM emp WHERE empno = p_empno;

case when salary >4000 then


set p_saltype ='Good';
when salary >3000 then
set p_saltype ='Fair';
else set p_saltype ='Poor';
end case;
END$$
delimiter ;

90
While loop

DELIMITER $$
CREATE PROCEDURE test_loop()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 1;
SET str = '';
WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;
SELECT str;
END$$
DELIMITER ;

91
FUNCTIONS

DELIMITER $$
CREATE FUNCTION
EMPFUN(p_creditLimit double) RETURNS VARCHAR(10) DETERMINISTIC
BEGIN
DECLARE lvl varchar(10);
IF p_creditLimit > 4000 THEN
SET lvl = 'Good';
ELSEIF p_creditLimit > 3000 THEN
SET lvl = 'FAIR';
else
SET lvl = 'POOR';
END IF;
RETURN (lvl);
END $$
delimiter ;

92
93
94
95
96
97
98
99
100
101

You might also like