Chapter 7 Introduction To MySQL
Chapter 7 Introduction To MySQL
Introduction to MySQL
Introduction
• MySQL, the most popular Open Source SQL
database management system, is developed,
distributed, and supported by Oracle Corporation.
• The SQL part of “MySQL” stands for “Structured
Query Language”.
• SQL is the most common standardized language
used to access databases.
2
MySQL Characteristics
• MySQL is a database system used on the web
• MySQL Server works in client/server or embedded systems
• MySQL is ideal for both small and large applications
• MySQL is very fast, reliable, scalable, and easy to use
• MySQL uses standard SQL statements
• MySQL compiles on a number of platforms
• MySQL is free to download and use
3
Definitions (1-3)
• A database is simply a structured collection of data which
is organized in such a way that its contents can easily be
accessed and manipulated.
• A database management system (DBMS), or database
engine as it is sometimes referred to, provides the
software used to store, retrieve and modify data in a
database.
4
Definitions (2-3)
• The data in MySQL is stored in database objects called tables.
• A table is a collection of related data, and it consists of columns and
rows.
• Each row of each table comprises a data record, which may contain
several fields of information. Term 'row' is synonymous with
'record', while 'column' is synonymous with 'field'. This is useful to
bear in mind when visualizing tables.
5
Definitions (3-3)
• Databases are useful when storing information
categorically. A company may have a database with the
following tables: "Employees", "Products", "Customers"
and "Orders".
6
Database Tables
• A database most often contains one or more tables. Each table is
identified by a name (e.g. "Customers" or "Orders"). Tables contain
records (rows) with data.
8
Manage Databases Using MySQL
• You can run mysql via MySQL console or command
prompt.
• MySQL console: open Xampp control panel, click on
Shell button:
• Syntax: mysql -u username -p -h hostname dbname
• Example: mysql -u root –p -h localhost mysql, then
enter password. You connected through root user,
localhost and mysql database.
9
Manage Databases Using MySQL
• To run mysql on command prompt:
1. Run cmd command
2. Use the drive you have installed XAMPP server (c:\ or
d:\)
3. Assuming you have installed Xampp on C:\ drive
4. C:\>cd xampp
5. C:\xampp>cd mysql
6. C:\xampp\mysql>cd bin
10
Manage Databases Using MySQL
7. C:\xampp\mysql\bin>mysql.exe -u root –p
8. Enter password
• You can enter all these command once as follows:
C:\ cd xampp\mysql\bin
Then enter:
mysql.exe -u root –p
• Now, you connected to the MySQL database.
11
Statements
• Show databases
• Choose database
• Show current database
• Create database
• Delete database
• Create table
12
Statements (cont…)
• Show tables
• Show fields from table
• Primary key
• Auto_increment fields
• Delete table
• Insert into statement
13
Statements (cont…)
• Select Statement
• The WHERE clause
• comparison operators (<, <=, >, >=, =, !=)
• Like Keyword
14
Statements (cont…)
• IN Keyword
• BETWEEN Keyword
• LIMIT Keyword
• Order By Keyword
• Order by Two Columns
15
Statements (cont…)
• Update Statement
• Delete Statement
• Alter statement
16
Create database
• You can query databases available by writing the following
query:
Show databases;
• Create a Database
• Syntax
CREATE DATABASE database_name;
17
• To show current database
select database ( );
• Choose the database you want to use, for example:
Use JARANE;
• To delete a database use DROP statement.
DROP DATABASE JARANE;
18
Create table
• Syntalx
• CREATE TABLE table_name
(
column_name1 data_type constraints,
column_name2 data_type constraints,
column_name3 data_type constraints,
....
);
19
For example
• For example, to create customer table in jarane database:
create table jarane.customer (id int, firstName varchar
(20), lastName varchar (20), age int);
• Note: When you create a field of type varchar, you must
specify its maximum length. The data type specifies what
type of data the column can hold.
• Note that a database must be selected before a table can
be created.
20
Show tables & columns
• To show all tables in the current database (for example,
JARANE):
Show tables (from JARANE);
• To see the design of any table:
Show columns from STUDENTS;
describe STUDENTS;
21
Primary key Constraint
• A primary key is used to uniquely identify the rows in a
table. Each primary key value must be unique within the
table. Furthermore, the primary key field cannot be null
because the database engine requires a value to locate the
record.
• The primary key field is often an ID number, and is often
used with the AUTO_INCREMENT setting.
• For example,
create table courses (no int not null primary key
auto_increment, name varchar (60) not null, description
varchar (200)); 22
SQL DEFAULT Constraint
• The DEFAULT constraint is used to provide a default value for
a column.
• The default value will be added to all new records IF no other
value is specified.
• Example,
create table students (id int, firstName varchar (20), lastName
varchar (20), age int, address varchar (100) default "Laba
Dhagax, Warta Nabadda");
23
Unique Constraint
• The unique constraint ensures that all values in a column are
different.
• For example,
create table students (id varchar(15) not null, name
varchar(100) unique);
24
Primary key vs unique
• Both the unique and primary key constraints provide a
guarantee for uniqueness for a column or set of columns. A
primary key constraint automatically has a unique
constraint. However, you can have many unique constraints
per table, but only one primary key constraint per table.
25
Create table as another table
• You can create new table with the same structure as an
existing table.
• For example
CREATE TABLE students LIKE myStudents;
26
Select statement
• To display data from the table use SELECT statement.
SELECT * From STUDENTS;
• N.B. An asterisk (*) stands for all columns.
27
Insert Into Statement
• The INSERT INTO statement is used to insert new records in
a table.
• Syntax
• It is possible to write the INSERT INTO statement in two
forms.
• The first form does not specify the column names where
the data will be inserted, only their values.
• For example,
INSERT INTO customers VALUES (5, 'Axmed', 'Faarax', 21);
28
Insert Into Statement (cont…)
• In this case you should insert values to every column
respectively.
• The second form specifies both the column names and the
values to be inserted.
• Example1:
INSERT INTO customer (ID, FirstName, LastName, Age)
VALUES (6, 'Maxamed', 'Faarax', 19);
29
Example
• Example2:
INSERT INTO customer (ID, FirstName, LastName, Age)
VALUES ('Xasan', "Caddaawe", '33');
30
Notes
• You can insert values to only the columns that you want.
• In varchar values you can use single or double quotes.
• When inserting date, enclose it with quotations (single or
double) in yyyy-mm-dd format.
insert into students values (3, 'Xasan', 'Yuusuf', 'Shibis',
'1990-12-28');
31
Notes (cont…)
• You can use curdate( ) function to insert current date.
insert into students values (2, 'Cabdifataax', 'Jaamac',
'Howlwadaag', curdate());
32
How to copy table data to another
• You can copy contents of a table another table provided they
are the same structure.
• For example
INSERT INTO students SELECT * FROM myStudents;
33
Select Statement
• The SELECT statement is used to select data from a
database.
• Syntax
SELECT column_name(s) FROM table_name
• Example:
SELECT firstName, lastName FROM customer;
• To show all columns data of the table:
SELECT * FROM customer;
34
Format date
• You can format date field as dd-mm-yyyy using
date_format( ) function as follows:
select stdNo, stdName, stdAddress,
date_format(stddob,'%d-%m-%y') AS TAARIIKHDA from
Students;
35
The WHERE clause
• The WHERE clause is used to (filter records) extract only
those records that fulfill a specified criterion.
• Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
36
The WHERE clause
• Use comparison operators (<, <=, >, >=, ==, !=) with WHERE
clause. If column value is text you should enclose it with
quotations (either single or double).
• Example1:
Select * from students Where stdName = "Maxamed";
• Example2:
Select * from students Where stdNo > 2;
37
Like Keyword
• The LIKE keyword is used to specify patterns to match
against.
• Example1: query all names starts with M from students.
SELECT * FROM STUDENTS WHERE stdName LIKE "M%";
• Example 2: query all names ends with d from students.
Select * from students where stdName like "%d";
38
In Keyword
• The IN keyword is used to filter records in the list provided.
• Example: query all employees whose salary is in the list.
Select * from employees where empSalary in (500, 600,
1000);
39
Between Keyword
• The BETWEEN keyword is used to select in between two
values inclusive.
• Example: query all employees whose salary in between
600 and 1000;
Select * from employees where empSalary between 600 and
1000;
40
Between Keyword (cont…)
• You can use AND/OR keyword to combine two conditions.
• Example: query all employees whose salary in between
400 and 600 or in the list (900, 1000).
Select * from employees where empSalary between 400
and 600 or empSalary in (900, 1000);
41
LIMIT Keyword
• The LIMIT keyword is used to limit selected rows.
• Example: query only 5 employees
Select * from employees limit 5;
• means select only first 5 records.
• Example:
Select * from employees limit 3, 6;
• means skip the first 3 records and show next 6 records.
42
Order by Keyword
• The ORDER BY keyword is used to sort the data in a
recordset. The ORDER BY keyword sorts the records in
ascending order by default.
• Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
43
Example
• Example: query all employees and sort them ascending by
names.
Select * from employees order by empName ASC;
• If you want to sort the records in a descending order, use
the DESC keyword. For example:
Select * from employees order by empName DESC;
44
Order by Two Columns
• When sorting by more than one column, the second
column is only used if the values in the first column are
equal.
• Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
• Example:
Select * from employees order by empName, empSalary;
45
Update Statement
• The UPDATE statement is used to modify existing records in
a table.
• Syntax
UPDATE table_name
SET column1 = value, column2 = value2,...
WHERE some_column = some_value
46
Example
• Example: rename employee with the name “Dhaqane”
and change it to “Xalane” and modify his salary into 510.
update employees set empName = "Xalane", empSalary =
510 where empName = "Dhaqane";
• Note: The WHERE clause specifies which record or records
should be updated. If you omit the WHERE clause, all
records will be updated!
47
Delete Statement
• The DELETE statement is used to delete records in a table.
• Syntax
DELETE FROM table_name
WHERE some_column = some_value
• Example: delete the employee with number 21.
delete from employees where empNo = 21;
48
Note
• The WHERE clause specifies which record or records should
be deleted. If you omit the WHERE clause, all records will
be deleted!
49
Alter Statement
• ALTER TABLE statement changes the structure of a table.
For example, you can
• add or delete columns
• add or remove constraints to columns
• change columns data type
• rename columns or
• Rename table
50
Add new column
• To add new column use add (column) statement:
Alter table students add stdage int;
• Alter statement adds the column at the end of the table by
default. However, you can add a column at any position in
the table.
51
Add new column (any position)
• To add a column after any column use after statement as
follows:
alter table students add stdregdate date after stdage;
• To add a column at the first use first statement as follows:
alter table students add stdage int first;
52
Delete column or change its data type
• Delete column
• To delete a column use drop (column) statement:
Alter table students drop column stdAddress;
• Change column data type
• To change stdNo data type from int to varchar (20) use
modify statement:
alter table students modify stdNo varchar (20);
53
Rename Column or Table
• To rename column name from stdNo to stdID use change
statement:
alter table students change stdNo stdID varchar (20);
• To rename the table from BIT_Students to BCS_Students
use rename (as) statement:
ALTER TABLE BIT_Students RENAME BCS_Students;
54
Note
• You can use one alter statement to do more than one job.
For example, drop two columns.
alter table students drop sn, drop nickname;
• or add new column and modify another column’s data
type.
alter table students add age int, modify id varchar (20);
55
Note
• You can use alter statement to change table constraints
such as primary key, default, unique, etc.
alter table students add primary key (id);
alter table students modify id int not null primary key;
alter table students drop primary key;
alter table students add unique (name);
56
Creating Users in MySQL
• You can create new user as follows:
create user 'jarane'@'localhost' identified by 'abc';
create user 'ali';
• To show current user:
select user ( );
• To show all users with their hosts:
SELECT USER, HOST FROM MYSQL.USER;
57
Creating Users in MySQL
• You can change password for the user, for example to
change jarane user's password:
set password for 'jarane'@'localhost' = password ('123');
set password for 'ali' = password ('123');
• where 123 is the new password for jarane and ali users.
• Grant all privileges to user:
GRANT all privileges on *.* TO 'jarane'@'localhost' WITH
GRANT OPTION;
• The WITH GRANT OPTION allows the user to grant or
revoke privileges to or from other users.
58
Creating Users in MySQL
• Show user privileges:
SHOW GRANTS FOR 'jarane'@'localhost';
• Grant CREATE permissions for all databases, and all tables,
to the user (abdi):
GRANT CREATE ON *.* TO 'abdi'@'localhost';
• Revoke all privileges from User:
Revoke all privileges ON *.* FROM 'jarane'@'localhost';
59
Deleting Users in MySQL
• To remove a user from MySQL, we again use
the DROP command. It only takes one simple command to
delete a user in MySQL, but BEWARE; dropping a user
cannot be undone! The command is as follows:
DROP USER 'abdi'@'localhost';
60
`
END
61