MYSQL AND SQL
Introduction
• A DB system is a computer based record keeping system.
• The collection of data is usually referred to as the database,
contains information about one particular enterprise.
• The database may also be defined as a collection of interrelated
data stored together to serve multiple applications.
Purpose of DBMS
• To manage data in a database we use database management
system.
• It provides a centralized control of the data, thereby minimizing
the problems-Data redundancy(Duplication of data), data
inconsistency(Multiple copies of same data, but not matching with
one another), un sharable data, incorrect data.
Advantages of Database systems
• Reduces data redundancy-Duplication of data
• Controls Data inconsistency-When data is not updated properly
• It facilitates sharing of data
• Integrity can be maintained through databases. (can only be
accessed or modified by those authorized to do so)
Relational Data Model
• A data model refers to a set of concepts to describe the structure of a database, and certain
constraints(restrictions) that the database should obey.
• The most commonly used data models are relational data model. Ex: MYSQL, SQLite,
Microsoft SQL Server etc.
• In relational data model, the data is organized into tables(Rows and columns). These tables
are called relations.
• A row in a table represents a relationship among a set of values.
• The terms used in relational model are:
• Relation-Tables
• Domain-Pool of values
• Tuple-Rows of tables
• Attributes-The columns of tables.
• Degree-The No. of Attributes in a relation determine the degree of a relation.
• Cardinality-The No. of tuples(rows) in a relation is called cardinality
• View-Virtual table-derived from the base tables
Relational Data Model
Relational Data Model
• Primary key-A set of one or more attributes having values that are unique
within the relation and thus are able to uniquely identify the tuple.
• In some tables, combination of more than one attribute provides a unique
value for each now. The primary key consists of more than one attribute, it
is called composite-primary-key.
• Candidate key-The attributes contain unique values in a table are called
candidate keys.
• Alternate key-In case of two or more candidate keys, only one of them
serves as the primary key. The rest of them are alternate keys.
• Foreign key-It is used to represent the relationship between two tables. It is
the primary key of some other table.
Referential Integrity
• It is a system of rules that a DBMS uses to ensure that relationships
between records in related tables are valid, and that users don’t
accidentally delete or change related data.
MYSQL
•MYSQL is a freely available open
source Relational Database
Management System, that uses
Structured Query Language.
•We can download from
www.mysql.org
MYSQL DB system
• The key role of a database management system is
information management.
• A DB server manages large amount of data in a multi-user environment so
that many users can concurrently access the same data and also prevent
unauthorized access and provide efficient solutions for failure recovery.
• MYSQL database system is the combination of a MYSQL server instance
and a MYSQL database. It operates on client/server architecture, where
server runs the machine containing database and clients connect to the
server over a network.
• The server OS is Linux or Windows or MacOS.
MySQL DB system
• Features of MySQL:
• Speed: It runs fast.
• Ease of use: It is relatively simple database system.
• Cost: It is for free
• Query Language Support: It understands Structured Query Language.
• Portability: It works on many different compilers and on different platforms.
• Data types: It supports many types of data, fixed length and variable length records.
• Security: It offers a privilege and passport system that is very flexible and secure.
• Scalability and Limits: It handles large database up to 50 million records.
• Connectivity: Clients can connect to MySQL server using several protocols.
• Localization: The server provides several error messages to clients in many languages.
• Clients and Tools: It provides several client and utility programs.
SQL
• In order to access data within the MYSQL database, all programs and users
must use, Structured Query Language(SQL).
• SQL provides many different commands, which are divided into following
categories.
• 1. DDL-Data Definition Language commands-Used to perform tasks related
to data definition:
• Creating, altering and dropping
• Granting and revoking privileges and roles
• Maintenance commands-Analyze table, check table repair table, restore table
• 2. DML-Data Manipulation Language commands-Used to perform data
manipulation. Eg. Retrieval, insertion , deletion and modification of data
• 3. TCL-Transaction Control Language commands-Used to manage and
control the transactions-Making changes permanent, Undoing changes etc.
Commit, rollback, savepoint, set transaction
MySQL SQL Elements
• Literals-Fixed data values: Character-“Hello”, numeric-12
• Data Types: Numeric, Date and Time, String types.
MySQL SQL Elements
MySQL SQL Elements
MySQL SQL Elements
MySQL SQL Elements
Char and Varchar
• Char data type specifies a fixed length character string.
• Varchar specifies a variable length string.
• Null value-If a column has no value, then column is said to be null.
• Null is not equal to Zero.
• (Null added to 10 is null)
• Comments:
• Multiple lines-/*
• */
• Single line: # or --
Accessing database in MYSQL
Create database if not exists student;
If the student database exists then creating database student is ignored.
Show databases- To display all the databases created.
Use <databasename>-To use a particular database that is created.
Drop database student-To remove database.
Creating table syntax:
Create table <table-name>
(<column name> <datatype>[(<size>)],<column name> <datatype> [(<size>)….]);
Ex:
Create table std
(scode integer,
sname varchar(20),
Gender char(1),
Dob date);
SQL Constraints
To ensure data integrity, constraints are used.
NOT NULL
DEFAULT
UNIQUE
CHECK- if the age is >5
PRIMARY KEY –alter table emp add primary key(ecode)
FOREIGN KEY-alter table dept add foreign key (dcode) references emp
(deptcode);
There are 2 types of constraints column constraints and Table constraints.
Column constraint applied to individual columns. Table constraint applied to
a group of one or more columns.
SQL Constraints
Check constraint-Used to limit values that can be
inserted into a column of a table.
SQL Constraints
Examples: pg.no. 578-581
SQL
Inserting data into a Table
Insert into <tablename>[<column list>]
Values (<value>,<value>…);
Ex:
Insert into emp Values(100,’Raghu’,55000);
Ex:
Insert into emp (ecode, ename) Values(101,’Raj’);
The salary column will have a default value or NULL value.
SQL
Alter table:
• To add a column
• To add a constraint
• To redefine a column
Alter table emp add (mobile integer);
Alter table emp add primary key( emp_id );
Alter table modify (ename char(30));
Adding not null constraint/default value
Alter table emp modify emp_salary decimal(10,2) not null;
Alter table emp modify emp_salary default 0;
SQL
Changing the order of attribute/Column:
Alter table emp modify emp_name first | after column_name;
Changing the column name:
Alter table change column ecode empcode varchar(30);
Dropping tables/database:
Drop database emp;
Drop table if exists emp;
Alter table emp drop column salary;
Alter table emp drop primary key, drop foreign key;
SQL
Modifying data in tables
Update emp Set ename= ‘Raasi’ Where ecode=1;
Deleting data from tables:
Delete from emp where ecode=100;
Delete from emp;
QUERIES
SELECT what_to_select from which_table WHERE conditions_to_satisfy;
Ex:
Select * from emp;
Select * from emp where ecode=100;
Select ecode, ename from emp;
Select distinct ename from emp;
Select 3.46*2;
Select salary*0.1 as “Increment”;
Select salary where salary between 20000 and 50000;
Select ename from emp where city in/not in(‘Hyd’, ’Delhi’);
Select ename from emp where ename like ‘r%’; (pattern matches)
Select ename from emp where ename like ‘____’
QUERIES
Aggregate Functions: Works on group of rows
Ex:
Select avg(salary) “average” from emp;
Select count(*) “total” from emp;
Select max(salary) from emp;
Select min(salary) from emp;
Select sum(salary) “total salary” from emp;
Group by:
Select * from emp group by salary;
Select salary from emp group by salary; nested groups
Select * from emp group by salary having deptcode=20 order by deptcode asc|desc;