Tot Webdev - SQL
Tot Webdev - SQL
Source: https://www.w3schools.com
Introduction to SQL
What is SQL?
● 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
Introduction to SQL
Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL
standard!
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.
The table above contains five records (one for each customer) and seven columns (CustomerID, CustomerName,
ContactName, Address, City, PostalCode, and Country).
SQL Syntax
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement selects all the records in the "Customers" table:
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
The following SQL statement selects all the records in the "Customers" table:
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.
SQL Syntax
Select
The SQL 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;
SQL Statements
Select
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
SQL Statements
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different
(distinct) values.
Database Tables
Below is a selection from the "Customers" table in the Northwind sample database:
SQL Statements
Now, let us use the SELECT DISTINCT statement and see the result.
SQL Statements
Note: The example above will not work in Firefox! Because COUNT(DISTINCT column_name) is not supported in
Microsoft Access databases. Firefox is using Microsoft Access in our examples.
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:
The selection from the "Customers" table will now look like this:
Did you notice that we did not insert any number into the CustomerID field?
The CustomerID column is an auto-increment field and will be generated automatically when a new record is
inserted into the table.
SQL Statements
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):
The selection from the "Customers" table will now look like this:
SQL Statements
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The
WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in
the table will be updated!
SQL Statements
UPDATE Table
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and a new
city.
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
The selection from the "Customers" table will now look like this:
SQL Statements
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The selection from the "Customers" table will now look like this:
SQL Statements
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
Example
UPDATE Customers
SET ContactName='Juan';
The selection from the "Customers" table will now look like this:
SQL Statements
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: 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!
SQL Statements
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
Example
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group
the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
SQL Statements
WHERE Syntax
SELECT column1, column2, …
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
Clauses
The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records
can impact performance.
Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a
limited number of records, while Oracle uses FETCH FIRST n ROWS ONLY and ROWNUM.
Clauses
Clauses
Clauses
The following SQL statement shows the equivalent example for MySQL:
The following SQL statement shows the equivalent example for Oracle:
The Result:
Clauses
The following SQL statement shows the equivalent example for Oracle:
The following SQL statement shows the equivalent example for MySQL:
The following SQL statement shows the equivalent example for Oracle:
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.
OR Syntax
NOT Syntax
AND Example
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is "Berlin":
Example
OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München":
Example
OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München":
The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
OR Example
The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
SELECT * FROM Customers
WHERE NOT Country='Germany';
The result will show all data but not the data that has Germany in the Country.
AND, OR, and NOT Operators
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city must be
"Berlin" OR "München" (use parenthesis to form complex expressions):
ORDER BY Syntax
SELECT column1, column2, …
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Order Keyword
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" column:
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!
Null Values
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;
The following SQL lists all customers with a NULL value in the "Address" field:
The following SQL lists all customers with a value in the "Address" field:
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Min() and Max(), Count(), Avg(), and Sum() Functions
MIN() Example
The following SQL statement finds the price of the cheapest product:
MAX() Example
The following SQL statement finds the price of the most expensive product:
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Min() and Max(), Count(), Avg(), and Sum() Functions
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Min() and Max(), Count(), Avg(), and Sum() Functions
COUNT() Example
The following SQL statement finds the number of products:
SELECT COUNT(ProductID)
FROM Products;
AVG() Example
The following SQL statement finds the average price of all products:
SELECT AVG(Price)
FROM Products;
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
SELECT SUM(Quantity)
FROM OrderDetails;
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;
Tip: You can also combine any number of conditions using AND or OR operators.
Like, In, and Between Operator
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
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);
Like, In, and Between Operator
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" or "UK":
IN Operator Examples
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Like, In, and Between Operator
BETWEEN Example
The following SQL statement selects all products with a price between 10 and 20:
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table.
The relationship between the two tables above is the "CustomerID" column.
Join Keyword
SQL JOIN
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that have
matching values in both tables:
● (INNER) JOIN: Returns records that have matching values in both tables
● LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records
from the right table
● RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table
● FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table
Inner Join
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns. If there are records in the "Orders" table that do not have matches in
"Customers", these orders will not be shown!
Inner Join
Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if there are
no matches in the right table (Orders).
Right Join
Note: The RIGHT JOIN keyword returns all records from the right table (Employees), even if there
are no matches in the left table (Orders).
Full Outer Join
Tip: FULL OUTER JOIN and FULL JOIN are the same.
Note: FULL OUTER JOIN can potentially return very large result-sets!
Full Outer Join
● 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;
Note: 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!
Union Operator
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table or a column a
temporary name. An alias only exists for the duration of the query. So, here we have created a
temporary column named "Type", that list whether the contact person is a "Customer" or a
"Supplier".
Getting a host and a domain name
SQL Hosting
If you want your web site to be able to store and retrieve data from a database, your web server should have
access to a database-system that uses the SQL language.
If your web server is hosted by an Internet Service Provider (ISP), you will have to look for SQL hosting plans.
The most common SQL hosting databases are MS SQL Server, Oracle, MySQL, and MS Access.
MS SQL Server
Microsoft's SQL Server is a popular database software for database-driven web sites with high traffic.
SQL Server is a very powerful, robust and full featured SQL database system.
Getting a host and a domain name
Oracle
Oracle is also a popular database software for database-driven web sites with high traffic.
Oracle is a very powerful, robust and full featured SQL database system.
MySQL
MySQL is also a popular database software for web sites.
MySQL is a very powerful, robust and full featured SQL database system.
MS Access
When a web site requires only a simple database, Microsoft Access can be a solution.
MS Access is not well suited for very high-traffic, and not as powerful as MySQL, SQL Server, or Oracle.
Source:
https://www.w3schools.com/css/default.asp
Thank you!