You are on page 1of 45

MySQL

Vidhya Vibha
About Me and
My Institute
Scope
 Career Scope
 Database Administrator
 Database Analyst
Learning Path

Database SQL SQL


Overview Process Syntax

SQL SQL SQL


Overview Command Function
Utilize Utilize the MySQL DBMS to build and modify relational databases with SQL

Add Add records to a MySQL database

Perform Perform intricate queries on database records with filters and groupings

Objective Create Create simple joins and unions within a database

Create Create relationships between tables using primary and foreign keys

Demonstrate Demonstrate the ability to complete a database normalization project


 A relational database management system (RDBMS)
is a collection of programs and capabilities that enable
us and others to create, update, administer and
Relational otherwise interact with a relational database. RDBMS
store data in the form of tables, with most commercial
Database relational database management systems using
Structured Query Language (SQL) to access the
Management database.

System  Each row of a relation/table represents a record, and


each column represents an attribute of data. The
(RDMS) Structured Query Language (SQL) is used to
manipulate relational databases. The design of a
relational database is composed of four stages, where
the data are modeled into a set of related tables.
 Data
 Database
 What is need of Database
 Types of Databases
Database  Distributed databases
 Relational databases
 Object-oriented databases
 Cloud databases
 Data warehouses
 SQL is Structured Query Language, which is a
computer language for storing, manipulating and
retrieving data stored in relational database.
 SQL is the standard language for Relation

SQL Overview Database System. All relational database


management systems like MySQL, MS Access,
Oracle, Sybase, Informix, postgres and SQL Server
use SQL as standard database language.
 MySQL is a very popular open-source relational
database management system (RDBMS).
SQL Process

 When you are executing an SQL command for any RDBMS, the
system determines the best way to carry out your request and SQL
engine figures out how to interpret the task.
 There are various components included in the process. These
components are Query Dispatcher, Optimization Engines, Classic
Query Engine and SQL Query Engine, etc. Classic query engine
handles all non-SQL queries, but SQL query engine won't handle
logical files.
What is a Database Table?
Scientist First Last Y.O.B Country
ID Name Name
A table is a collection of related data
1 Sir Venkata Raman 1888 India
entries, and it consists of columns and
Chandrasekhara
rows.
2 Homi Jehangir Bhabha 1909 India

4
A column holds specific information
about every record in the table.

A record (or row) is each individual


entry that exists in a table.
SQL Command

SQL commands are instructions. It is used to communicate with the database.


It is also used to perform specific tasks, functions, and queries of data.

SQL can perform various tasks like create a table, add data to tables, drop the
table, modify the table, set permission for users.
Types of SQL Commands

SQL  There are five types of SQL


Commands
commands
(DDL) DML DCL TCL DQL
• Data Definition Language (DDL)
Create Insert Grant Commit Select
• Data Manipulation Language (DML)
Drop Update Revoke Rollback
• Data Control Language (DCL)
Alter Delete Save Point • Transaction Control Language (TCL)
Truncate • Data Query Language (DQL)
Data Definition Language Command Description
(DDL)
Create Create a new table, a view
 DDL changes the structure of the of a table, or other object in
table like creating a table, deleting database.
a table, altering a table, etc.
 All the command of DDL are auto- Alter Modifies an existing
committed that means it
permanently save all the changes
database object, such as
in the database. table
Drop Deletes an entire table, a
view of a table or other
object in the database.
Data Manipulation
Language (DML)
Command Description
 DML commands are used to modify the Insert Create a record
database. It is responsible for all form of
changes in the database. Update Modifies records
 The command of DML is not auto-committed
that means it can't permanently save all the Delete Deletes record
changes in the database. They can be rollback.
Command Description
Data Control Grant Give a privilege to user to
Language perform certain task.
(DCL) Revoke Take back privileges
DCL commands are used to granted from user.
grant and take back authority
from any database user.
Command Description
Transaction Control
Commit Commit command is used to
Language (TCL)
permanently save any transaction
 Transaction Control Language into the database.
commands are used to manage
transactions in the database. These are
used to manage the changes made by Rollback This command restores the
DML-statements. It also allows
statements to be grouped together into
database to last committed state. It
logical transactions. is also used with savepoint
 TCL commands can only use with command to jump to a savepoint in
DML commands like INSERT,
DELETE and UPDATE only. a transaction.
 These operations are automatically
committed in the database that's why
they cannot be used while creating
Savepoint Savepoint command is used to
tables or dropping them. temporarily save a transaction so
that you can rollback to that point
whenever necessary.
Command Description
Data Query Select Retrieves
Language certain record
(DQL) from one or
DQL statements are used for more tables.
performing queries on the data.
 The data type of a column defines what value
the column can hold: integer, character, money,
date and time, binary, and so on.
 In MySQL there are three main data types:
SQL Data Types  String,
 Numeric,
 and Date and Time.
 Date and time
Create Schema/ Database
Syntax Description
CREATE {DATABASE | SCHEMA} [IF CREATE DATABASE creates a database with
NOT EXISTS] the given name. To use this statement, you need
the CREATE privilege for the database.
To List All Databases In MySQL
Syntax Description
SHOW {DATABASES | SCHEMAS} SHOW DATABASES lists the databases on the
MySQL server host.
DROP Database
Syntax Description
 DROP {DATABASE | SCHEMA} [IF  DROP DATABASE drops all tables in the
EXISTS] db_name database and deletes the database.
 Be very careful with this statement! To use
DROP DATABASE, you need the DROP
privilege on the database.
 Example
 DROP DATABASE training;
Create Table
The CREATE TABLE statement is used to
create a new table in a database. Description
Syntax The column parameters specify the names of the
columns of the table.
CREATE TABLE table_name (
The datatype parameter specifies the type of data
column1 datatype,
the column can hold (e.g. varchar, integer, date,
column2 datatype, etc.).
column3 datatype, Example

.... CREATE TABLE Students ( StudentID int,


LastName varchar(255), FirstName varchar(255),
); Age INT, grade INT);
Practice Example

Pet Table Show Table Describe Table


CREATE TABLE pet (name mysql> SHOW TABLES; mysql> DESCRIBE pet;
VARCHAR(20), owner
VARCHAR(20), species
VARCHAR(20), sex CHAR(1),
birth DATE, death DATE);
DROP TABLE Statement
Syntax Description
 DROP [TEMPORARY] TABLE [IF  DROP TABLE removes one or more tables.
EXISTS] tbl_name [, You must have the DROP privilege for each
tbl_name] ... table.
 Example
DROP TABLE Student;
Loading Data into a Table
Insert Syntax Description
 Generic Statement  The SQL INSERT INTO Statement is used to add new rows of
data to a table in the database.
 INSERT INTO tbl_name () VALUES();  It is possible to write the INSERT INTO statement in two ways:
 INSERT INTO table_name (column1, c  1. Specify both the column names and the values to be inserted:

olumn2, column3, ...)  Example


INSERT INTO STUDENT (ID,NAME,AGE,ADDRESS, FEES) VALUES
VALUES (value1, value2, value3, .. (1011, 'Ramesh’, 22, 'Ahmedabad', 2000.00 );

.);  If you are adding values for all the columns of the table, you do not
need to specify the column names in the SQL query. However, make
 INSERT INTO table_name sure the order of the values is in the same order as the columns in
the table.
VALUES (value1, value2, value3, ..  Example for staff table
.); INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
SQL DROP or DELETE Table
Syntax Description
 DROP [TEMPORARY] TABLE [IF  The SQL DROP TABLE statement is used to
EXISTS] tbl_name [, remove a table definition and all data,
tbl_name] ... [RESTRICT | indexes, triggers, constraints, and permission
CASCADE] specifications for that table.
 DROP TABLE removes one or more tables.
TRUNCATE TABLE
Syntax Description
 TRUNCATE [TABLE] tbl_name  The MySQL TRUNCATE TABLE statement allows
you to delete all data in a table.
 Logically, the TRUNCATE TABLE statement is like
a DELETE statement without a WHERE clause that
deletes all rows from a table, or a sequence of
DROP TABLE and CREATE TABLE statements.
 However, the TRUNCATE TABLE statement is
more efficient than the DELETE statement because
it drops and recreates the table instead of deleting
rows one by one.
SELECT statement
Syntax Description
 SELECT select_list FROM table_name;  SELECT is used to retrieve rows selected from
one or more tables.
 SELECT * FROM table_name;
 When executing the SELECT statement,
 SELECT column1, column2, ...
MySQL evaluates the FROM clause before the
FROM table_name; SELECT clause.
 Use the SELECT * to select data from all
columns of a table.
 Use the SELECT statement to select data from a
table.
Select Statement
 SELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN]
[SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_NO_CACHE]
[SQL_CALC_FOUND_ROWS] select_expr [, select_expr] ... [into_option] [FROM
table_references [PARTITION partition_list]] [WHERE where_condition] [GROUP
BY {col_name | expr | position}, ... [WITH ROLLUP]] [HAVING where_condition]
[WINDOW window_name AS (window_spec) [, window_name AS (window_spec)] ...]
[ORDER BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]]
[LIMIT {[offset,] row_count | row_count OFFSET offset}] [into_option] [FOR
{UPDATE | SHARE} [OF tbl_name [, tbl_name] ...] [NOWAIT | SKIP LOCKED] |
LOCK IN SHARE MODE] [into_option] into_option: { INTO OUTFILE 'file_name'
[CHARACTER SET charset_name] export_options | INTO DUMPFILE 'file_name' |
INTO var_name [, var_name] ... }
WHERE Clause
Syntax Description
 SELECT select_list FROM table_name  The WHERE clause is used to filter records.
It is used to extract only those records that
WHERE search_condition;
fulfill a specified condition.
 SELECT column1, column2, ...
 You can specify a condition using comparison
FROM table_name
or logical operators like >, =,< etc.
WHERE condition;
UPDATE Query
 UPDATE table_name  The SQL UPDATE Query is used to
SET column1 = value1, colu modify the existing records in a
mn2 = value2, ... table.
WHERE condition;  You can use WHERE clause with
UPDATE query to update selected
rows, otherwise all the rows would
be affected.
 Syntax  The SQL DELETE Query is used to
 DELETE FROM table_name WHERE delete the existing records from a
 condition; table.
 Example  You can use WHERE clause with
 DELETE FROM Student WHERE DELETE query to delete selected
StudentId = 4; rows, otherwise all the records
would be deleted.

DELETE Statement
SQL LIKE Clause / SQL LIKE Operator

 The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There
are two wildcards used in conjunction with the LIKE operator:
 SELECT column1, column2, ...  The percent sign (%)
FROM table_name  The underscore (_)
WHERE columnN LIKE pattern;  The percent sign represents zero, one, or multiple characters. The underscore represents a single
number or character. The symbols can be used in combinations.

LIKE Operator Description

WHERE StudentName LIKE 'a%' Finds any values that start with "a"

WHERE StudentName LIKE '%a' Finds any values that end with "a"

WHERE StudentName LIKE '%or%' Finds any values that have "or" in any position

WHERE StudentName LIKE '_r%' Finds any values that have "r" in the second position

WHERE StudentName LIKE 'a_%' Finds any values that start with "a" and are at least 2 characters in length

WHERE StudentName LIKE 'a__%' Finds any values that start with "a" and are at least 3 characters in length

WHERE StudentName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
 SQL has many built-in functions for performing processing on string or numeric data. Following is the list of all useful SQL
built-in functions
 SQL COUNT Function - The SQL COUNT aggregate function is used to count the number of rows in a database table.
 SQL MAX Function - The SQL MAX aggregate function allows us to select the highest (maximum) value for a certain
column.
 SQL MIN Function - The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain
column.
 SQL AVG Function - The SQL AVG aggregate function selects the average value for certain table column.
 SQL SUM Function - The SQL SUM aggregate function allows selecting the total for a numeric column.
 SQL SQRT Functions - This is used to generate a square root of a given number.
 SQL RAND Function - This is used to generate a random number using SQL command.
 SQL CONCAT Function - This is used to concatenate any string inside any SQL command.
 SQL Numeric Functions - Complete list of SQL functions required to manipulate numbers in SQL.
 SQL String Functions - Complete list of SQL functions required to manipulate strings in SQL.

SQL Function
SQL Aggregate Functions
• SQL aggregate functions return a single value, calculated from values in a column.
• Useful aggregate functions:
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• FIRST() - Returns the first value

SQL
• LAST() - Returns the last value
• MAX() - Returns the largest value
• MIN() - Returns the smallest value

Function
• SUM() - Returns the sum
SQL Scalar functions

Type
• SQL scalar functions return a single value, based on the input value.
• Useful scalar functions:
• UCASE() - Converts a field to upper case
• LCASE() - Converts a field to lower case
• MID() - Extract characters from a text field
• LEN() - Returns the length of a text field
• ROUND() - Rounds a numeric field to the number of decimals specified
• NOW() - Returns the current system date and time
• FORMAT() - Formats how a field is to be displayed
SQL Functions Example
 COUNT() Syntax
 Description
 SELECT COUNT(column_name)
FROM table_name  The COUNT() function returns the
WHERE condition;
 AVG() Syntax
number of rows that matches a
 SELECT AVG(column_name)
specified criterion.
FROM table_name
WHERE condition;
 The AVG() function returns the
 SUM() Syntax average value of a numeric column.
 SELECT SUM(column_name)  The SUM() function returns the total
FROM table_name
WHERE condition; sum of a numeric column.
Function Description  MySQL comes with the following
NOW() Returns the current date and time data types for storing a date or a
CURDATE() Returns the current date date/time value in the database:
CURTIME()Returns the current time  DATE - format YYYY-MM-DD
DATE() Extracts the date part of a date or date/time expression  DATETIME - format: YYYY-MM-
EXTRACT() Returns a single part of a date/time DD HH:MI:SS
DATE_ADD() Adds a specified time interval to a date  TIMESTAMP - format: HH:MI:SS
DATE_SUB() Subtracts a specified time interval from a date  YEAR - format YYYY or YY
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats
MONTH(date) Returns the month part for a given date (i.e from 1 -
12).

Working With Dates


LIMIT SYNTAX
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
DISTINCT SYNTAX
SELECT DISTINCT column1, column2, ...
FROM table_name;
BETWEEN SYNTAX
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
ORDER BY SYNTAX

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
ALTER SYNTAX
3) DROP column in table
1) ADD a column in the table
ALTER TABLE table_name
ALTER TABLE table_name DROP COLUMN column_name;
ADD column_name datatype;    ...  ;
4) RENAME column in table
2) MODIFY column in the table
ALTER TABLE table_name
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;   CHANGE COLUMN OldcolumnName NewcolumNname
datatype;
ALIAS SYNTAX
Alias for columns Alias for tables
SELECT column_name AS alias_name  SELECT column_name(s)
FROM table_name; FROM table_name AS alias_name;
STRING FUNCTIONS
 Length(string): This function returns the length of the string, in bytes
 REPLACE(string, from_string, new_string): This function replaces a string or
character(s)
 POSITION(substring IN string): This function finds the position of the character
 REVERSE(string): This function reverses a string and returns the result
UNQUE CONSTRAINTS
 The UNIQUE constraint ensures that all values in a column are different.
 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.

You might also like