Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 50

MySQL SQL

WHAT IS SQL?
 SQL IS THE STANDARD LANGUAGE FOR DEALING WITH RELATIONAL DATABASES.
 SQL IS USED TO INSERT, SEARCH, UPDATE, AND DELETE DATABASE RECORDS.
 SQL IS A STANDARD LANGUAGE FOR ACCESSING AND MANIPULATING DATABASES.
 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
SQL is a Standard - BUT....

 Although SQL is an ANSI/ISO standard, there are different versions of the SQL language.

 However, to be compliant with the ANSI standard, they all support at least the major commands
(such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.

 Note: Most of the SQL database programs also have their own proprietary extensions in
addition to the SQL standard!
Using SQL in Your Web Site

 To build a web site that shows data from a database, you will need:
 An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
 To use a server-side scripting language, like PHP or ASP
 To use SQL to get the data you want
 To use HTML / CSS to style the page
RDBMS

 RDBMS stands for Relational Database Management System.


 RDBMS is the basis for SQL, and for all modern database systems such as MS SQL
Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
 The data in RDBMS is stored in database objects called tables. A table is a collection of
related data entries and it consists of columns and rows.
 Example
 SELECT * FROM Customers;
Customer table.

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Emparedados Ana Trujillo Avda. de la Constitución México D.F. 05021 Mexico
y helados 2222

3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany

7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France

8 Bólido Comidas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain


preparadas
Field and records

 Every table is broken up into smaller entities called fields. The fields in the Customers table consist of CustomerID,
CustomerName, ContactName, Address, City, PostalCode and Country. A field is a column in a table that is
designed to maintain specific information about every record in the table.
 A record, also called a row, is each individual entry that exists in a table. For example, there are 91 records in the
above Customers table. A record is a horizontal entity in a table.
 A column is a vertical entity in a table that contains all information associated with a specific field in a table.
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.
 In this tutorial we will use the well-known Northwind sample database (included in MS Access and MS SQL
Server).
 Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución 2222
helados

3 Antonio Moreno Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería
SQL Statements

 Most of the actions you need to perform on a database are done with SQL statements.

Example
SELECT
 The following SQL * FROM
statement selectsCustomers;
all the records in the "Customers" table:
 Keep in Mind That...
 SQL keywords are NOT case sensitive: select is the same as SELECT
Semicolon after SQL Statements?

 Some database systems require a semicolon at the end of each SQL statement.
 Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL
statement to be executed in the same call to the server.
 For example :
 Select * from customer;
 Here * is used to select all the data from customer table and display the entire record from it .
 Select is the command to display the informations.
 From will tell you that from where you have to select the data or information.
Some of The Most Important SQL Commands

 SELECT - extracts data from a database


 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
MySQL SELECT Statement

 The MySQL SELECT Statement


 The SELECT statement is used to select data from a database.
 The data returned is stored in a result table, called the result-set.
 SELECT Syntax:
 SELECT column1, column2, ...
FROM table_name;
 Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select all the
fields available in the table, use the following syntax:
 SELECT * FROM table_name;
Demo Database

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedados y Constitución 2222
helados

3 Antonio Moreno Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
Taquería

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden


SELECT Columns Example

 The following SQL statement selects the "CustomerName", "City", and "Country" columns from the "Customers"
table:
 Example
 SELECT CustomerName, City, Country FROM Customers;

CustomerName City Country


Alfreds Futterkiste Berlin Germany
Ana Trujillo Emparedados y México D.F. Mexico
helados
Antonio Moreno Taquería México D.F. Mexico
The MySQL SELECT DISTINCT Statement

 The SELECT DISTINCT statement is used to return only distinct (different) values.
 Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different
(distinct) values.
SELECT DISTINCT Syntax:
SELECT DISTINCT column1, column2, ...
FROM table_name;
 SELECT DISTINCT Examples
 The following SQL statement selects only the DISTINCT values from the "Country" column in the "Customers"
table:
 Example:
 SELECT DISTINCT Country FROM Customers;
SELECT Example Without DISTINCT

 The following SQL statement selects all (including the duplicates) values from the "Country" column in the
"Customers" table:
 Example
 SELECT Country FROM Customers;
 The following SQL statement counts and returns the number of different (distinct) countries in the "Customers" table:
 Example:
 SELECT COUNT(DISTINCT Country) FROM Customers;
MySQL WHERE Clause

 The MySQL WHERE Clause


 The WHERE clause is used to filter records.
 It is used to extract only those records that fulfill a specified condition.
 WHERE Syntax
 SELECT column1, column2, ...FROM table_name WHERE condition;
 WHERE Clause Example
 The following SQL statement selects all the customers from "Mexico":
 Example
 SELECT * FROM Customers
WHERE Country = 'Mexico';

 Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
Text Fields vs. Numeric Fields

 SQL requires single quotes around text values (most database systems will also allow double quotes).
 However, numeric fields should not be enclosed in quotes:
 Example
 SELECT * FROM Customers
WHERE CustomerID = 1;

CustomerID CustomerNa ContactNam Address City PostalCode Country


me e
1 Alfreds Maria Obere Str. Berlin 12209 Germany
Futterkiste Anders 57
Operators in The WHERE Clause

Operator Description

= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=

BETWEEN Between a certain range


LIKE Search for a pattern
IN To specify multiple possible values for a column
Equal to Operators in The WHERE Clause

 SELECT * FROM Products


WHERE Price = 18;

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 bags 18.00

35 Steeleye Stout 16 1 24 - 12 oz bottles 18.00

39 Chartreuse verte 18 1 750 cc per bottle 18.00

76 Lakkalikööri 23 1 500 ml 18.00


Greater than (>)

 SELECT * FROM Products


WHERE Price > 30;

ProductID ProductName SupplierID CategoryID Unit Price

8 Northwoods 3 2 12 - 12 oz jars 40.00


Cranberry Sauce

9 Mishi Kobe Niku 4 6 18 - 500 g pkgs. 97.00

10 Ikura 4 8 12 - 200 ml jars 31.00

12 Queso Manchego La 5 4 10 - 500 g pkgs. 38.00


Pastora

17 Alice Mutton 7 6 20 - 1 kg tins 39.00


Less than (<)

 SELECT * FROM Products


WHERE Price < 30;

ProductID ProductName SupplierID CategoryID Unit Price


1 Chais 1 1 10 boxes x 20 bags 18.00

2 Chang 1 1 24 - 12 oz bottles 19.00

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10.00

4 Chef Anton's Cajun 2 2 48 - 6 oz jars 22.00


Seasoning
Greater than equal to (>=)

 SELECT * FROM Products


WHERE Price >= 30;

ProductID ProductName SupplierID CategoryID Unit Price


7 Uncle Bob's Organic 3 7 12 - 1 lb pkgs. 30
Dried Pears
8 Northwoods Cranberry 3 2 12 - 12 oz jars 40
Sauce
9 Mishi Kobe Niku 4 6 18 - 500 g pkgs. 97
10 Ikura 4 8 12 - 200 ml jars 31
Less than equal to (<=)

 SELECT * FROM Products


WHERE Price <= 30;

ProductID ProductName SupplierID CategoryID Unit Price


1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

4 Chef Anton's Cajun 2 2 48 - 6 oz jars 22


Seasoning

5 Chef Anton's Gumbo 2 2 36 boxes 21.35


Mix
Not equal. (< >)

 Note: In some versions of SQL this operator may be written as !=


SELECT * FROM Products
WHERE Price <> 18;

ProductID ProductName SupplierID CategoryID Unit Price


2 Chang 1 1 24 - 12 oz bottles 19
3 Aniseed Syrup 1 2 12 - 550 ml bottles 10
4 Chef Anton's Cajun 2 2 48 - 6 oz jars 22
Seasoning
5 Chef Anton's Gumbo 2 2 36 boxes 21.35
Mix
6 Grandma's Boysenberry 3 2 12 - 8 oz jars 25
Spread
SQL BETWEEN Operator

 The SQL BETWEEN Operator


 The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
 The BETWEEN operator is inclusive: begin and end values are included.
 BETWEEN Syntax
 SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Demo Database

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

4 Chef Anton's Cajun 1 2 48 - 6 oz jars 22


Seasoning

5 Chef Anton's Gumbo 1 2 36 boxes 21.35


Mix
BETWEEN Example

 The following SQL statement selects all products with a price between 10 and 20:
 Example
 SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

ProductID ProductName SupplierID CategoryID Unit Price

1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

15 Genen Shouyu 6 2 24 - 250 ml bottles 15.5

16 Pavlova 7 3 32 - 500 g boxes 17.45

21 Sir Rodney's Scones 8 3 24 pkgs. x 4 pieces 10

25 NuNuCa Nuß-Nougat- 11 3 20 - 450 g glasses 14


Creme
NOT BETWEEN Example

 To display the products outside the range of the previous example, use NOT BETWEEN:
 Example
 SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;

ProductID ProductName SupplierID CategoryID Unit Price


4 Chef Anton's Cajun 2 2 48 - 6 oz jars 22
Seasoning
5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

6 Grandma's Boysenberry 3 2 12 - 8 oz jars 25


Spread
7 Uncle Bob's Organic 3 7 12 - 1 lb pkgs. 30
Dried Pears
BETWEEN with IN Example

 The following SQL statement selects all products with a price between 10 and 20. In addition; do not show products
with a CategoryID of 1,2, or 3:
 Example
 SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);

ProductID ProductName SupplierID CategoryID Unit Price


31 Gorgonzola Telino 14 4 12 - 100 g pkgs 12.5
36 Inlagd Sill 17 8 24 - 250 g jars 19
40 Boston Crab Meat 19 8 24 - 4 oz tins 18.4
42 Singaporean Hokkien 20 5 32 - 1 kg pkgs. 14
Fried Mee
BETWEEN Text Values Example

 The following SQL statement selects all products with a ProductName between Carnarvon Tigers and Mozzarella di
Giovanni:
 Example
 SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;

 The following SQL statement selects all products with a ProductName between Carnarvon Tigers and Chef Anton's Cajun
Seasoning:
 Example
 SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;
NOT BETWEEN Text Values Example

 The following SQL statement selects all products with a ProductName not between Carnarvon Tigers and
Mozzarella di Giovanni:
 Example
 SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Sample table or Demo table

OrderID CustomerID EmployeeID OrderDate ShipperID

10248 90 5 7/4/1996 3

10249 81 6 7/5/1996 1

10250 34 4 7/8/1996 2

10251 84 3 7/9/1996 1

10252 76 4 7/10/1996 2
BETWEEN Dates Example

 The following SQL statement selects all orders with an OrderDate between '01-July-1996' and '31-July-1996':
 Example
 SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;

Or
 Example
 SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
Between a certain range (BETWEEN)

 SELECT * FROM Products


WHERE Price BETWEEN 50 AND 60;

ProductID ProductName SupplierID CategoryID Unit Price

51 Manjimup Dried 24 7 50 - 300 g pkgs. 53


Apples
59 Raclette 28 4 5 kg pkg. 55
Courdavault
Search for a pattern (LIKE)

 SELECT * FROM Customers


WHERE City LIKE 's%'; ( this will return a city which starts from word S in that city )
Note : by using this command you can find tha data of that particular later which you want to see from your table .

CustomerID CustomerName ContactName Address City PostalCode Country

7 Blondel père et Frédérique 24, place Strasbourg 67000 France


fils Citeaux Kléber
15 Comércio Pedro Afonso Av. dos São Paulo 05432-043 Brazil
Mineiro Lusíadas, 23
21 Familia Aria Cruz Rua Orós, 92 São Paulo 05442-030 Brazil
Arquibaldo
The SQL LIKE Operator

 The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
 There are two wildcards often used in conjunction with the LIKE operator:
 The percent sign (%) represents zero, one, or multiple characters
 The underscore sign (_) represents one, single character
 Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question mark (?) instead of the
underscore (_).
 The percent sign and the underscore can also be used in combinations!
 LIKE Syntax:
 SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Like operators

LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position

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

WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2
characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3
characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with
"o"
SQL LIKE Examples

 The following SQL statement selects all customers with a CustomerName starting with "a“:
 Example
 SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
 The following SQL statement selects all customers with a CustomerName ending with "a":
 Example
 SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
 The following SQL statement selects all customers with a CustomerName that have "or" in any position:
 Example
 SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
SQL Like operators :

 The following SQL statement selects all customers with a CustomerName that have "r" in the second position:
 Example
 SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
 The following SQL statement selects all customers with a CustomerName that starts with "a" and are at least 3 characters in length:
 Example
 SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
 The following SQL statement selects all customers with a ContactName that starts with "a" and ends with "o":
 Example
 SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
 The following SQL statement selects all customers with a CustomerName that does NOT start with "a":
 Example

 SELECT * FROM Customers


WHERE CustomerName NOT LIKE 'a%';
To specify multiple possible values for a column
(IN)
 SELECT * FROM Customers
WHERE City IN ('Paris', 'London');
city

19 Eastern Connection Ann Devon 35 King George London WX3 6FW UK

53 North/South Simon Crowther South House 300 London SW7 1RZ UK


Queensbridge

57 Paris spécialités Marie Bertrand 265, boulevard Paris 75012 France


Charonne

72 Seven Seas Imports Hari Kumar 90 Wadhurst Rd. London OX15 4NB UK

74 Spécialités du monde Dominique Perrier 25, rue Lauriston Paris 75016 France
The SQL IN Operator

 The IN operator allows you to specify multiple values in a WHERE clause.


 The IN operator is a shorthand for multiple OR conditions.
 IN Syntax
 SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
 or:
 SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Demo Database:

CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany

2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico

3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico

4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK

5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

6 Blauer See Delikatessen Hanna Moos Forsterstr. 57 Mannheim 68306 Germany

7 Blondel père et fils Frédérique Citeaux 24, place Kléber Strasbourg 67000 France

8 Bólido Comidas preparadas Martín Sommer C/ Araquil, 67 Madrid 28023 Spain


IN Operator Examples

 The following SQL statement selects all customers that are located in "Germany", "France" or "UK":
 Example
 SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
 The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
 Example
 SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
SQL NULL Values

 A field with a NULL value is a field with no value.


 If a field in a table is optional, it is possible to insert a new record or update
a record without adding a value to this field. Then, the field will be saved
with a NULL value.
 Note: A NULL value is different from a zero value or a field that contains
spaces. A field with a NULL value is one that has been left blank during
record creation!
How to insert null in table

 create database student2;


 use student
 create table attendance (fname varchar(10) , sname char(10) not null );
 select * from attendance
 insert into attendance values ('Venkat',Null)
 insert into attendance (sname,fname) values ('Sagar','Joshi')
 insert into attendance (fname) values ('Joshi')
 insert into attendance values ('Venkat','Joshi'),('Sagar','Iyer')
How to Test for NULL Values?

 It is not possible to test for NULL values with comparison operators, such as =, <, or <>. !=
 We will have to use the IS NULL and IS NOT NULL operators instead.
 IS NULL Syntax:
 SELECT column_names
FROM table_name
WHERE column_name IS NULL;

 IS NOT NULL Syntax:


 SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Examples

 Example
 SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

 The IS NOT NULL Operator:


 SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
MySQL IFNULL() Function

 MySQL IFNULL function is one of the MySQL control flow functions that accepts two arguments and returns the
first argument if it is not NULL. Otherwise, the IFNULL function returns the second argument.
 The two arguments can be literal values or expressions.
 The following illustrates the syntax of the IFNULL function:
 IFNULL(expression_1,expression_2);
 CREATE TABLE contacts ( contactid INT AUTO_INCREMENT PRIMARY KEY, contactname
VARCHAR(20) NOT NULL, bizphone VARCHAR(15), homephone VARCHAR(15));
 INSERT INTO contacts(contactname,bizphone,homephone)VALUES('John Doe','(541) 754-3009',NULL),
('Cindy Smith',NULL,'(541) 754-3110'), ('Sue Greenspan','(541) 754-3010','(541) 754-3011'), ('Lily
Bush',NULL,'(541) 754-3111');
 SELECT contactName, bizphone, homephone FROM contacts;
 SELECT contactname, IFNULL(bizphone, homephone) phone FROM contacts;

You might also like