0% found this document useful (0 votes)
16 views57 pages

Presentation 1

The document provides an overview of MySQL including what it is, who uses it, how to use SQL to interact with relational databases, and descriptions of important SQL commands and clauses like WHERE, ORDER BY, JOINs, and aggregation functions.

Uploaded by

umesh rane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views57 pages

Presentation 1

The document provides an overview of MySQL including what it is, who uses it, how to use SQL to interact with relational databases, and descriptions of important SQL commands and clauses like WHERE, ORDER BY, JOINs, and aggregation functions.

Uploaded by

umesh rane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

21.

The MySQL BETWEEN Operator


1. What is MySQL? 22. MySQL Aliases
2. Who Uses MySQL? 23. The MySQL UNION Operator
3. Show Data On Your Web Site 24. MySQL UNIQUE Constraint
4. What is RDBMS? 25. MySQL PRIMARY KEY Constraint
5. What is a Relational Database? 26. MySQL FOREIGN KEY Constraint
6. What is SQL? 27. SQL | Join (Inner, Left, Right and Full
7. How to Use SQL Joins)
8. Some of the Most Important SQL Commands
9. The MySQL WHERE Clause
10. The MySQL AND, OR and NOT Operators
11. The MySQL ORDER BY Keyword
12. The MySQL INSERT INTO Statement
13. MySQL NULL Values
14. The MySQL UPDATE Statement
15. The MySQL DELETE Statement
16. The MySQL LIMIT Clause
17. MySQL MIN() and MAX() Functions
18. MySQL COUNT(), AVG() and SUM() Functions
19. The MySQL LIKE Operator
20. The MySQL IN Operator
1. What is MySQL?
• MySQL is a relational database management system
• MySQL is very fast, reliable, scalable, and easy to use

2. Who Uses MySQL?


• Huge websites like Facebook, Twitter, Airbnb, Booking.com, Uber, GitHub, YouTube, etc.
• Content Management Systems like Word Press, Drupal, and Joomla! Contao, etc.
• A very large number of web developers around the world

3.Show Data On Your Web Site:-


• To build a web site that shows data from a database, you will need:
• An RDBMS database program (like MySQL)
• A server-side scripting language, like PHP
• To use SQL to get the data you want
• To use HTML / CSS to style the page

4. What is RDBMS?
• RDBMS stands for Relational Database Management System.
• RDBMS is a program used to maintain a relational database.
• RDBMS is the basis for all modern database systems such as MySQL, Microsoft SQL Server,
Oracle, and Microsoft Access.
• RDBMS uses SQL queries to access the data in the database.
5. What is a Relational Database?

A relational database defines database relationships in the form of tables. The tables are related
to each other - based on data common to each.
Example:- Customers Table

CustomerID CustomerName ContactName Address City PostalCode Country

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

2 Ana Trujillo Emparedados y Ana Trujillo Avda. de la Constitución México D.F. 05021 Mexico
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


Orders Table
OrderID CustomerID EmployeeID OrderDate ShipperID

10278 5 8 1996-08-12 2

10280 5 2 1996-08-14 1

10308 2 7 1996-09-18 3

10355 4 6 1996-11-15 1

10365 3 3 1996-11-27 2

10383 4 8 1996-12-16 3

10384 5 3 1996-12-16 3

The relationship between the "Customers" table and the "Orders" table is the CustomerID
column
Shippers Table

ShipperID ShipperName Phone

1 Speedy Express (503) 555-9831

2 United Package (503) 555-3199

3 Federal Shipping (503) 555-9931

The relationship between the "Orders" table and the "Shippers" table is the ShipperID
column
6. What is SQL?
•SQL is the standard language for dealing with Relational Databases.
•SQL is used to insert, search, update, and delete database records.

7. How to Use SQL


The following SQL statement selects all the records in the "Customers" table:
•SELECT Syntax:-
SELECT column1, column2, ...
FROM table_name;
If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
Example
SELECT * FROM Customers;
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
•SQL keywords are NOT case sensitive: select is the same as SELECT

8. 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

9. The MySQL WHERE Clause

The WHERE clause is used to filter records.


It is used to extract only those records that fulfil a specified condition.

WHERE Syntax:-
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Text Fields vs. Numeric Fields:-
• SQL requires single quotes around text values (most database systems will also allow
double quotes).
SELECT * FROM Customers
WHERE Country = 'Mexico';

• However, numeric fields should not be enclosed in quotes:


Example:-
SELECT * FROM Customers
WHERE CustomerID = 1;

CustomerID CustomerName ContactName Address City PostalCode Country

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


• Operators in the WHERE Clause
The following operators can be used 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


10. The MySQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
•The AND operator displays a record if all the conditions separated by AND are TRUE.
•The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.

• AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

• AND Example
The following SQL statement selects all fields from "Customers" where country is "Germany"
AND city is "Berlin":
Example
SELECT * FROM Customers
WHERE Country = 'Germany' AND City = 'Berlin';

• OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
OR Example

The following SQL statement selects all fields from "Customers" where city is "Berlin" OR
"Stuttgart":

Example
SELECT * FROM Customers
WHERE City = 'Berlin' OR City = 'Stuttgart';

• NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
Example
SELECT * FROM Customers
WHERE NOT Country = 'Germany';

Combining AND, OR and NOT


You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is "Germany"
AND city must be "Berlin" OR "Stuttgart" (use parenthesis to form complex expressions):
• SELECT * FROM Customers
WHERE Country = 'Germany' AND (City = 'Berlin' OR City = 'Stuttgart');

• SELECT * FROM Customers


WHERE NOT Country = 'Germany' AND NOT Country = 'USA';

11. The MySQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.

• ORDER BY Syntax

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

• ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:

Example
SELECT * FROM Customers
ORDER BY Country;
CustomerID CustomerName ContactName Address City PostalCode Country

12 Cactus Comidas para llevar Patricio Simpson Cerrito 333 Buenos Aires 1010 Argentina

54 Océano Atlántico Ltda. Yvonne Moncada Ing. Gustavo Moncada 8585 Piso 20- Buenos Aires 1010 Argentina
A

64 Rancho grande Sergio Gutiérrez Av. del Libertador 900 Buenos Aires 1010 Argentina

20 Ernst Handel Roland Mendel Kirchgasse 6 Graz 8010 Austria

59 Piccolo und mehr Georg Pipps Geislweg 14 Salzburg 5020 Austria

50 Maison Dewey Catherine Dewey Rue Joseph-Bens 532 Bruxelles B-1180 Belgium

76 Suprêmes délices Pascale Cartrain Boulevard Tirou, 255 Charleroi B-6000 Belgium

• ORDER BY DESC Example

The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:

Example
SELECT * FROM Customers
ORDER BY Country DESC;
• ORDER BY Several Columns Example

The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column. This means that it orders by Country, but if some
rows have the same Country, it orders them by CustomerName:

Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;

• ORDER BY Several Columns Example 2

The following SQL statement selects all customers from the "Customers" table, sorted ascending
by the "Country" and descending by the "CustomerName" column:

Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
12. The MySQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax


It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

2. 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 sure the order of the values is in the same
order as the columns in the table. Here, the INSERT INTO syntax would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

INSERT INTO Example


The following SQL statement inserts a new record in the "Customers" table:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName Address City PostalCode Country

89 White Clover Karl Jablonski 305 - 14th Ave. S. Seattle 98128 USA
Markets Suite 3B

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

92 Cardinal Tom B. Erichsen Skagen 21 Stavanger 4006 Norway

• Insert Data Only in Specified Columns

It is also possible to only insert data in specific columns.


The following SQL statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated automatically):

Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
• The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName Address City PostalCode Country

89 White Clover Karl Jablonski 305 - 14th Ave. Seattle 98128 USA
Markets S. Suite 3B

90 Wilman Kala Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland

91 Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland

92 Cardinal null null Stavanger null Norway

13. MySQL NULL Values

What is a NULL Value?

• 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.
• 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 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.

• The IS NULL Operator


The IS NULL operator is used to test for empty values (NULL values).

• IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;

• The following SQL lists all customers with a NULL value in the "Address" field:
Example

SELECT CustomerName, ContactName, Address


FROM Customers
WHERE Address IS NULL;

CustomerName ContactName Address


Wilman Kala Matti Karttunen NULL
• The IS NOT NULL Operator

The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).

• IS NOT NULL Syntax

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

• The following SQL lists all customers with a value in the "Address" field:

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

Alfreds Futterkiste Maria Anders Obere Str. 57

Ana Trujillo Emparedados Ana Trujillo Avda. de la Constitución 2222


y helados

Antonio Moreno Taquería Antonio Moreno Mataderos 2312


14. The MySQL UPDATE Statement

• The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
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 05021 Mexico


Emparedados y helados Constitución 2222 D.F.

UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Alfred Schmidt Obere Str. 57 Frankfurt 12209 Germany

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


Emparedados y helados Constitución 2222

Update Warning!

Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
Example

UPDATE Customers
SET PostalCode = 00000;

The selection from the "Customers" table will now look like this:
CustomerID CustomerName ContactName Address City PostalCode Country

1 Alfreds Futterkiste Alfred Schmidt Obere Str. 57 Frankfurt 00000 Germany

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


Emparedados y Constitución 2222
helados

3 Antonio Moreno Antonio Moreno Mataderos 2312 México D.F. 00000 Mexico
Taquería
15. The MySQL DELETE Statement

The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;

Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause,
all records in the table will be deleted!

Below is a selection from the "Customers" table in the Northwind sample :-

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 05021 Mexico
y helados 2222 D.F.

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

The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:

Example

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';


CustomerID CustomerName ContactName Address City PostalCode Country

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

• Delete All Records


It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:

DELETE FROM table_name;


The following SQL statement deletes all rows in the "Customers" table, without deleting the
table:
Example
DELETE FROM Customers;
16. The MySQL LIMIT Clause

The LIMIT clause is used to specify the number of records to return.


The LIMIT clause is useful on large tables with thousands of records. Returning a large number
of records can impact performance.

LIMIT Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

MySQL LIMIT Examples


The following SQL statement selects the first three records from the "Customers" table:
Example
SELECT * FROM Customers
LIMIT 3;
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
• ADD a WHERE CLAUSE

The following SQL statement selects the first three records from the "Customers" table, where
the country is "Germany":

Example

SELECT * FROM Customers


WHERE Country='Germany'
LIMIT 3;
Number of Records: 3

CustomerID CustomerName ContactName Address City PostalCode Country

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

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

17 Drachenblut Sven Ottlieb Walserweg 21 Aachen 52066 Germany


Delikatessend
17. MySQL MIN() and MAX() Functions

The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.

•MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;

MIN() Example

The following SQL statement finds the price of the cheapest product:
Example

SELECT MIN(Price) AS SmallestPrice


FROM Products;
SmallestPrice

2.50

• MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
• MAX() Example
The following SQL statement finds the price of the most expensive product:

Example

SELECT MAX(Price) AS LargestPrice


FROM Products;

LargestPrice

263.50

18. MySQL COUNT(), AVG() and SUM() Functions

I. The COUNT() function returns the number of rows that matches a specified criterion.
• COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

• COUNT() Example
The following SQL statement finds the number of products:
Example

SELECT COUNT(ProductID)
FROM Products;
COUNT(ProductID)

77

NULL values are ignored.

II. The AVG() function returns the average value of a numeric column.
• AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

Example
SELECT AVG(Price)
FROM Products;
AVG(Price)

28.866364

III. The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Example
SELECT SUM(Quantity)
FROM OrderDetails;

SUM(Quantity)

51317

19. The MySQL 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.
• The percent sign and the underscore can also be used in combinations!

You can also combine any number of conditions using AND or OR operators.

percent sign and the underscore can also be used in combinations!

LIKE Syntax:-

SELECT column1, column2, ...


FROM table_name
WHERE columnN LIKE pattern;
Here are some examples showing different LIKE operators with '%' and '_' wildcards:

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"
20. The MySQL 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);

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');
CustomerID CustomerName ContactName Address City PostalCode Country

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

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

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

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

• 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');
CustomerID CustomerName ContactName Address City PostalCode Country

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

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


snabbköp

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


preparadas
• The following SQL statement selects all customers that are from the same countries as the
suppliers:

Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
CustomerID CustomerName ContactName Address City PostalCode Country

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

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

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


snabbköp

6 Blauer See Hanna Moos Forsterstr. 57 Mannheim 68306 Germany


Delikatessen

21. The MySQL 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;
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.00

2 Chang 1 1 24 - 12 oz bottles 19.00

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10.00

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.00


Seasoning

5 Chef Anton's Gumbo 2 2 36 boxes 21.35


Mix

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


Spread

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.50

36 Inlagd Sill 17 8 24 - 250 g jars 19.00

40 Boston Crab Meat 19 8 24 - 4 oz tins 18.40


22. MySQL Aliases
• Aliases are used to give a table, or a column in a table, a temporary name.
• Aliases are often used to make column names more readable.
• An alias only exists for the duration of that query.
• An alias is created with the AS keyword.

Alias Column Syntax:-


SELECT column_name AS alias_name
FROM table_name;

Alias Table Syntax:-


SELECT column_name(s)
FROM table_name AS alias_name;

Alias for Columns Examples:-

The following SQL statement creates two aliases, one for the CustomerID column and one for
the CustomerName column:

SELECT CustomerID AS ID, CustomerName AS Customer


FROM Customers;
The following SQL statement creates two aliases, one for the CustomerName column and one for
the ContactName column:

Example:-
SELECT CustomerName AS Customer, ContactName AS "Contact Person"
FROM Customers;

Single or double quotation marks are required if the alias name contains spaces

The following SQL statement creates an alias named "Address" that combine four columns
(Address, PostalCode, City and Country):

Example:-
SELECT CustomerName, CONCAT_WS(', ', Address, PostalCode, City, Country) AS Address
FROM Customers;

• Alias for Tables Example


• The following SQL statement selects all the orders from the customer with CustomerID=4
(Around the Horn). We use the "Customers" and "Orders" tables, and give them the table
aliases of "c" and "o" respectively (Here we use aliases to make the SQL shorter):

Example:-
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
The following SQL statement is the same as above, but without aliases:

Example:-
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the
Horn' AND Customers.CustomerID=Orders.CustomerID;

• Aliases can be useful when:


• There are more than one table involved in a query
• Functions are used in the query
• Column names are big or not very readable
• Two or more columns are combined together

23. The MySQL UNION Operator


The UNION operator is used to combine the result-set of two or more SELECT statements.

• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order

UNION Syntax:-
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Example:-
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

If some customers or suppliers have the same city, each city will only be listed once,
because UNION selects only distinct values. Use UNION ALL to also select duplicate values!

SQL UNION ALL Example:-


The following SQL statement returns the cities (duplicate values also) from both the
"Customers" and the "Suppliers" table:

City
Aachen

Albuquerque

Barcelona

Barquisimeto
Example:-
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
City
Aachen

Albuquerque

Anchorage
Bergamo

Berlin

Berlin

• SQL UNION With WHERE

The following SQL statement returns the German cities (only distinct values) from both the
"Customers" and the "Suppliers" table:

Example:-

SELECT City, Country FROM Customers


WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
City Country
Aachen Germany

Berlin Germany

Brandenburg Germany

Cunewalde Germany

Cuxhaven Germany
24. MySQL UNIQUE Constraint

• 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.
• However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.

• UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL, Field Type Null Key
FirstName varchar(255),
Age int, ID int(11) NO PRI

UNIQUE (ID)
); LastName varchar(255) NO

FirstName varchar(255) YES

Age int(11) YES


25. MySQL PRIMARY KEY Constraint

• The PRIMARY KEY constraint uniquely identifies each record in a table.

• Primary keys must contain UNIQUE values, and cannot contain NULL values.

• A table can have only ONE primary key; and in the table, this primary key can consist of single
or multiple columns (fields).

•PRIMARY KEY on CREATE TABLE


• The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:

CREATE TABLE Persons ( FIELD TYPE NULL KEY


ID int NOT NULL,
LastName varchar(255) NOT NULL, ID int(11) NO PRI
FirstName varchar(255),
Age int,
PRIMARY KEY (ID) LastName varchar(255) NO
);

FirstName varchar(255) YES

Age int(11) YES


• PRIMARY KEY on ALTER TABLE

To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use
the following SQL:

ALTER TABLE Persons


ADD PRIMARY KEY (ID);

•DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons


DROP PRIMARY KEY;

26. MySQL FOREIGN KEY Constraint

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in
another table.

The table with the foreign key is called the child table, and the table with the primary key is
Persons Table

PersonID LastName FirstName Age

1 Hansen Ola 30

2 Svendson Tove 23

3 Pettersen Kari 20

Orders Table

OrderID OrderNumber PersonID

1 77895 3

2 44678 3

3 22456 2

4 24562 1
•Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
•The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
•The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
•The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.

• FOREIGN KEY on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is
created:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

• FOREIGN KEY on ALTER TABLE


To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is
already created, use the following SQL:

ALTER TABLE Orders


• DROP a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:

ALTER TABLE Orders


DROP FOREIGN KEY FK_PersonOrder;

27. SQL | Join (Inner, Left, Right and Full Joins):-

A SQL Join statement is used to combine data or rows from two or more tables based on a
common field between them. Different types of Joins are:

1. INNER JOIN

2. LEFT JOIN

3. RIGHT JOIN

4. FULL JOIN

Consider the two tables below:


Student

StudentCourse
1. INNER JOIN:

The INNER JOIN keyword selects all rows from both the tables as long as the condition satisfies.
This keyword will create the result-set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be same.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Example Queries(INNER JOIN):-

This query will show the names and age of students enrolled in different courses.

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student


INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;

Output:
2.LEFT JOIN:

This join returns all the rows of the table on the left side of the join and matching rows for the
table on the right side of join. The rows for which there is no matching row on right side, the
result-set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
Example Queries(LEFT JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:-
3. RIGHT JOIN:

RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of
the join and matching rows for the table on the left side of join. The rows for which there is no
matching row on left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT
OUTER JOIN.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Example Queries(RIGHT JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:-
4. FULL JOIN:-

FULL JOIN creates the result-set by combining result of both LEFT JOIN and RIGHT JOIN. The
result-set will contain all the rows from both the tables. The rows for which there is no
matching, the result-set will contain NULL values.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;
Example Queries(FULL JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:
28. What is a Stored Procedure?
• A stored procedure is a prepared SQL code that you can save, so the code can be reused over
and over again.
• So if you have an SQL query that you write over and over again, save it as a stored procedure,
and then just call it to execute it.
• You can also pass parameters to a stored procedure, so that the stored procedure can act
based on the parameter value(s) that is passed.

Example:-

CREATE DEFINER=`root`@`localhost` PROCEDURE `PCM`()


BEGIN
SELECT * FROM ihms.pay_client_master;
END

Execution:-
call pcm;

You might also like