Database
Database
A database is an organized collection of data, so that it can be easily accessed and managed. You can
organize data into tables, rows, columns, and index it to make it easier to find relevant information.
There are many databases available like MySQL, Sybase, Oracle, MongoDB, Informix, PostgreSQL, SQL
Server, etc.
MySQL
MySQL is a relational database management system based on the Structured Query Language, which is the
popular language for accessing and managing the records in the database. MySQL is open-source and free
software under the GNU license. It is supported by Oracle Company.
Syntax :
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Example :
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Syntax :
FROM existing_table_name
WHERE ....;
The following SQL creates a new table called "TestTables" (which is a copy of the "Customers" table):
Example :
FROM customers;
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
also used to add and drop various constraints on an existing table.
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
The following SQL deletes the "Email" column from the "Customers" table:
To change the data type of a column in a table, use the following syntax:
Customer
CustomerName ContactName Address City PostelCode Country
ID
Berglunds
1 Alfreds Futterkiste Maria Anders snabbköpObere Berlin 12209 Germany
Str. 57
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno Antonio
3 Mataderos 2312 México D.F. 05023 Mexico
Taquería Moreno
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds Christina
5 Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp Berglund
SELECT * Example
The following SQL statement selects ALL the columns from the "Customers" table:
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.
The following SQL statement counts and returns the number of different (distinct) countries in the
"Customers" table:
Output : 4
Example :
Customer
CustomerName ContactName Address City PostelCode Country
ID
Berglunds
1 Alfreds Futterkiste Maria Anders snabbköpObere Berlin 12209 Germany
Str. 57
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno Antonio
3 Mataderos 2312 México D.F. 05023 Mexico
Taquería Moreno
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds Christina
5 Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp Berglund
Tom
6 Cardinal Skagen 21 Stavanger 4006 Norway
B.Erichsen
Example :
FROM table_name
WHERE condition;
Example : SELECT * FROM Customers
Customer
CustomerName ContactName Address City PostelCode Country
ID
Ana Trujillo
Avda. de la
2 Emparedados y Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
helados
Antonio Moreno Antonio
3 Mataderos 2312 México D.F. 05023 Mexico
Taquería Moreno
SQL requires single quotes around text values (most database systems will also allow double quotes).
However, numeric fields should not be enclosed in quotes:
WHERE CustomerID = 1;
Customer
CustomerName ContactName Address City PostelCode Country
ID
Berglunds
1 Alfreds Futterkiste Maria Anders snabbköpObere Berlin 12209 Germany
Str. 57
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
MySQL UPDATE Statement
WHERE condition;
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person and a new city.
WHERE CustomerID = 2;
Customer
CustomerName ContactName Address City PostelCode Country
ID
Berglunds
1 Alfreds Futterkiste Maria Anders snabbköpObere Berlin 12209 Germany
Str. 57
Avda. de la
2 Alfred Schmidt Ana Trujillo México D.F. 05021 Mexico
Constitución 2222
Antonio Moreno Antonio
3 Mataderos 2312 México D.F. 05023 Mexico
Taquería Moreno
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds Christina
5 Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp Berglund
Tom
6 Cardinal Skagen 21 Stavanger 4006 Norway
B.Erichsen
It is the WHERE clause that determines how many records will be updated.
The following SQL statement will update the PostalCode to 00000 for all records where
country is "Mexico":
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
Customer
CustomerName ContactName Address City PostelCode Country
ID
Avda. de la
2 Alfred Schmidt Ana Trujillo México D.F. 00000 Mexico
Constitución 2222
Antonio Moreno Antonio
3 Mataderos 2312 México D.F. 00000 Mexico
Taquería Moreno
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Berglunds Christina
5 Berguvsvägen 8 Luleå S-958 22 Sweden
snabbköp Berglund
Tom
6 Cardinal Skagen 21 Stavanger 4006 Norway
B.Erichsen
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:
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.
FROM table_name
ORDER BY Country;
The following SQL statement selects all customers from the "Customers" table, sorted DESCENDING by the
"Country" column:
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
FROM table_name
WHERE condition;
FROM table_name
WHERE condition;
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
FROM Products;
SmallestPrice
2.50
FROM Products;
LargestPrice
21.35
The COUNT() function returns the number of rows that matches a specified criterion.
FROM table_name
WHERE condition;
FROM table_name
WHERE condition;
FROM table_name
WHERE condition;
Example : SELECT COUNT(ProductID)
FROM Products;
COUNT(ProductID)
15
Note: NULL values are not counted.
FROM Products;
AVG(Price)
18.07
Note: NULL values are ignored.
FROM OrderDetails;
SUM(Price)
90.35
Note: NULL values are ignored.
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!
FROM table_name
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
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
Finds any values that start with "a" and are at least 2 characters in
WHERE CustomerName LIKE 'a_%'
length
Finds any values that start with "a" and are at least 3 characters in
WHERE CustomerName LIKE 'a__%'
length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
MySQL IN Operator
FROM table_name
or:
SELECT column_name(s)
FROM table_name
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.
FROM table_name
ORDER BY ProductName;
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;
Example : SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
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.
The following SQL statement creates two aliases, one for the CustomerName column and one for the
ContactName column. Note: Single or double quotation marks are required if the alias name contains
spaces:
Example
The following SQL statement creates an alias named "Address" that combine four columns (Address,
PostalCode, City and Country):
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
Example
A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.
The SQL INNER JOIN joins two tables based on a common column, and selects records that have matching
values in these columns.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT Customers.customer_id, Customers.first_name, Orders.amount
FROM Customers
INNER JOIN Orders
ON Customers.customer_id = Orders.customer;
MySQL LEFT JOIN joins two tables based on a common column, and selects records that have matching
values in these columns and remaining rows from the left table.
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT Customers.customer_id, Customers.first_name, Orders.amount
FROM Customers
LEFT JOIN Orders
ON Customers.customer_id = Orders.customer;
MySQL RIGHT JOIN joins two tables based on a common column, and selects records that have matching
values in these columns and remaining rows from the right table.
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
MySQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate
functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
HAVING Example
SELECT City, SUM(Salary) as TotalSalary
FROM Employee
GROUP BY City
HAVING City = 'London';