Mysql
Mysql
What is data?
What is the difference between data and
information?
What is a database?
Examples of databases around you
What is a DBMS?
Collection of related data.
For eg. University database might contain
information about the following:
Entities such as Student, Faculty, Course,
Classroom Relationship between those entities
Some properties of Database:
Database represents some aspects of real world.
It is logically coherent collection of data with
some inherent meaning.
A database is designed , built , populated with
data for a specific purpose. It has intended
group of users and preconceived application.
Data Information Knowledge Action
RELATION: A table of values
A relation may be thought of as a set of rows/tuples
A relation may alternately be though of as a set of columns
Each row represents a fact that corresponds to a real-world
entity or relationship
Each row has a value of an item or set of items that
uniquely identifies that row in the table
Each column typically is called by its column name or
column header or attribute name
Each value of an attribute is derived from an
appropriate domain/type
The database schema corresponds to variable declarations in programs
Schema – the overall design/logical structure of database.
Schema Diagram:
Student:
NAME St_no Class Major
• It is a declarative rather than procedural language, which means that users declare
what they want without having to write a step-by-step procedure.
• The SQL language was first implemented by the Oracle Corporation in 1979, with
various versions of SQL being released since then.
• Application programs generally access databases through one of
– Language extensions to allow embedded SQL
– Application program interface (e.g., ODBC/JDBC) which allow SQL queries
to be sent to a database
Resources for practice:
http://sqlzoo.net/
http://www.mysqltutorial.org/basic-mysql-tutorial.aspx
http://www.w3schools.com/sql/
http://www.sqlcourse.com/
http://sol.gfxile.net/g3/
MySQL is a very popular, open source database.
Officially pronounced “my Ess Que Ell” (not my
sequel).
Handles very large databases; very fast
performance.
Why are we using MySQL?
Free (much cheaper than Oracle!)
Each student can install MySQL locally.
Easy to use Shell for creating tables, querying tables,
etc.
Easy to use with Java JDBC
23
The Data Definition Language (DDL) part of SQL permits
database tables to be created or deleted. We can also define
indexes (keys), specify links between tables, and impose
constraints between database tables.
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
26
To get started on your own database, first check
which databases currently exist.
Use the SHOW statement to find out which
databases currently exist on the server:
28
An SQL relation is defined using the create table
command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
r is the name of the relation
each Ai is an attribute name in the schema of
relation r
Di is the data type of attribute Ai
Example:
create table branch
(branch_name char(15),
branch_city char(30),
assets integer)
char(n). Fixed length character string, with user-specified
length n
varchar(n). Variable length character strings, with user-
specified maximum length n
int. Integer (a finite subset of the integers that is machine-
dependent)
smallint. Small integer (a machine-dependent subset of the
integer domain type)
numeric(p,d). Fixed point number, with user-specified
precision of p digits, with n digits to the right of decimal
point.
real, double precision. Floating point and double-precision
floating point numbers, with machine-dependent precision
float(n). Floating point number, with user-specified
precision of at least n digits
date(yyyymmdd). Holds a date in the format „yyyy-mm-dd‟ .
Method sysdate() is used to return current date in MySQL
Domain Types in SQL
Create a table ‘pets’ with following
attributes:
33
To view a table structure, use the DESCRIBE
command:
34
By default, newly created table is empty
The INSERT INTO statement is used to insert new rows into a table.
Syntax
INSERT INTO table_name
VALUES (value1, value2,....)
You can also specify the columns for which you want to insert data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)
Use the INSERT statement to enter data
into a table.
For example:
OR
After table creation:
ALTER TABLE Persons ADD UNIQUE (P_Id);
The PRIMARY KEY constraint uniquely
identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL
values.
Each table should have a primary key, and
each table can have only one primary key.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
);
PERSONS
Ai represents an attribute
Ri represents a relation
P is a predicate.
OR
SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy
55
You can select only particular rows from
your table.
For example, if you want to verify the
change that you made to Bowser's birth
date, select Bowser's record like this:
mysql> SELECT * FROM pet WHERE name = "Bowser";
+--------+-------+---------+------+------------+---------
---+
| name | owner | species | sex | birth | death
|
+--------+-------+---------+------+------------+---------
---+
| Bowser | Diane | dog | m | 1998-08-31 | 1995-07-
29 |
+--------+-------+---------+------+------------+---------
---+
1 row in set (0.00 sec)
56
Ifyou don‟t want to see entire rows from
your table, just name the columns in which
you are interested, separated by commas.
57
mysql> select name, birth from pet;
+----------+------------+
| name | birth |
+----------+------------+
| Fluffy | 1999-02-04 |
| Claws | 1994-03-17 |
| Buffy | 1989-05-13 |
| Fang | 1999-08-27 |
| Bowser | 1998-08-31 |
| Chirpy | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim | 1996-04-29 |
+----------+------------+
8 rows in set (0.01 sec)
58
Operator Precedence:
()
NOT
AND, &&
OR, ||
BETWEEN, IN, LIKE
The AND operator displays a record if both
the first condition AND the second condition
are true.
The OR operator displays a record if either
the first condition OR the second condition is
true.
62
The IN operator allows you to specify
multiple values in a WHERE clause.
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
SELECT * FROM Customers
WHERE City IN ('Paris','London');
The BETWEEN operator selects values within
a range. The values can be numbers, text, or
dates.
SQL BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND v
alue2;
List in alphabetic order the names of all customers
having a loan in Perryridge branch
select distinct customer-name
from loan
where
branch-name = ‘Perryridge’
order by customer-name
We may specify desc for descending order or asc for
ascending order, for each attribute; ascending order
is the default.
E.g. order by customer-name desc
It is possible for tuples to have a null value, denoted by
null, for some of their attributes
null signifies an unknown value or that a value does not
exist.
The predicate is null can be used to check for null
values.
E.g. Find all loan number which appear in the loan relation
with null values for amount.
select loan-number
from loan
where amount is null
The result of any arithmetic expression involving null is
null
E.g. 5 + null returns null
However, aggregate functions simply ignore nulls
more on this shortly
SQL includes a string-matching operator for comparisons on character
strings. Patterns are described using two special characters:
percent (%). The % character matches any substring.
underscore (_). The _ character matches any character.
Find the names of all customers whose street includes the substring
“Main”.
select customer-name
from customer
where customer-street like ‘%Main%’
Match the name “Main%”
like ‘Main\%’ escape ‘\’
The opposite of like operation is performed by „not like’
SQL supports a variety of string operations such as
concatenation (using “||”)
converting from upper to lower case (and vice versa)
finding string length, extracting substrings, etc.
Return all actors living in Mumbai
Return all actors whose age is more than 35
Return all actors whose age is more than 35 and who live in
Mumbai
Return the name and age of all actors
Return all actors in decreasing order of their age
Return the addresses of the actors having age between 20-30
Return the names of actors over 35 who live in Mumbai OR LA
Return names of all actors that have the string “is” in their name
Return all actors with a address starting with any character,
followed by “umbai"
The SQL allows renaming relations and
attributes using the as clause:
old-name as new-name
Find the name, loan number and loan
amount of all customers; rename the column
name loan-number as loan-id.
We want to add a first name to the person with a last name of "Rasmussen":
UPDATE Person SET FirstName = 'Nina'
WHERE LastName = 'Rasmussen'
We want to change the address and add the name of the city:
UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen'
or
78
These functions operate on the multiset of values
of a column of a relation, and return a value
SELECTcolumn_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
Findthe number of depositors for each branch.
select branch-name, count (distinct customer-
name)
from depositor
group by branch-name
Note: Attributes in select clause outside of
aggregate functions must appear in group by list
SELECT ENAME, AVG(SALARY)
FROM EMPLOYEE GROUP BY
DEPT ;
For Example:
CREATE TABLE suppliers AS (SELECT * FROM companies
WHERE id > 1000);
This would create a new table called suppliers that
includes all columns from the companies table
If there were records in the companies table, then the
new suppliers table would also contain the records
selected by the SELECT statement.