Manuale SQL Esempio Uni
Manuale SQL Esempio Uni
Syntax
Example
Syntax
Note: Be careful before dropping a database. Deleting a database will result in loss of complete
information stored in the database!
Example
1
The SQL CREATE TABLE Statement
The CREATE TABLE statement isused to create a new table in a database.
Syntax
The column parameters specify the names of the columns of the table.
The data type parameter specifies the type of data the column can hold (e.g. varchar, integer, date,
etc.).
Example
The LastName, FirstName, Address, and City columns are of type varchar and will hold characters,
and the maximum length for these fields is 255 characters.
2
The SQL DROP TABLE Statement
The DROP TABLE statement isused to drop an existing table in a database.
Syntax
Example
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
3
ALTER TABLE - ALTER/MODIFY COLUMN
To change the data type of a column in a table, use the following syntax:
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data
type specifies what type of data the column can hold. For a complete reference of all the data types
available in MS Access, MySQL, and SQL Server, go to our complete Data Types reference.
4
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or
four-digit format.
5
SQL constraints are used to specify rules for data in a table.
Syntax
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and
reliability of the data in the table. If there is any violation between the constraint and the data action,
the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and
table level constraints apply to the whole table.
NOT NULL – Ensures that a column can not have a NULL value
UNIQUE – Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
FOREIGN KEY – Uniquely identifies a row/record in another table
CHECK – Ensures that all values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column when no value is specified
INDEX - Used to create and retrieve data from the database very quickly
6
SQL NOT NULL Constraint
By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you can not insert a new record,
or update a record without adding a value to this field.
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept
NULL values:
Example
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns.
However, you can havemany UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
7
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values, and can not contain NULL values.
A table can have only one primarykey, which may consist of single or multiple fields.
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns, use the following SQL syntax:
8
DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
9
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
10
SQL DEFAULT Constraint
The DEFAULT constraint is used to provide a default value for a column.
The default value will be added to all new records IF no other value is specified.
11
SQL CREATE INDEX Statement
The CREATE INDEX statement isused to create indexes in tables.
Indexes are used to retrieve data from the database very fast. The users can not see the indexes, they
are just used to speed up searches/queries.
If you want to create an index on a combination of columns, you can list the column names within
the parentheses, separated by commas:
12
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
SELECT Syntax
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:
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
13
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
Inside a table, a column often contains many duplicate values; and sometimes you only want to list
the different (distinct) values.
The SELECT DISTINCT statement is used to return only distinct (different) values.
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
14
SELECT Example
The following SQL statement selects all (and duplicate) values from the "Country" column in the
"Customers" table:
Example
Now, let us use the DISTINCT keyword with the above SELECT statement and see the result.
Example
The following SQL statement lists the number of different (distinct) customer countries:
Example
The WHERE clause is used to extract only those records that fulfill a specified condition.
WHERE Syntax
Note: The WHERE clause is not only used in SELECT statement, it is also used in UPDATE,
DELETE statement, etc.!
15
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
Example
16
Operators in The WHERE Clause
The following operators can be used in the WHERE clause:
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
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 is TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
AND Syntax
OR Syntax
NOT Syntax
17
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
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
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
18
Example
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):
Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany"
and NOT "USA":
Example
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
19
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
Example
Example
20
Example
Example
The first way specifies both the column names and the values to be inserted:
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. The INSERT INTO syntax would be as follows:
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
90 Matti
Wilman Kala Keskuskatu 45 Helsinki 21240 Finland
Karttunen
21
INSERT INTO Example
The following SQL statement inserts a new record in the "Customers" table:
Example
The selection from the "Customers" table will now look like this:
90 Matti
Wilman Kala Keskuskatu 45 Helsinki 21240 Finland
Karttunen
Tom B.
92 Cardinal Skagen 21 Stavanger 4006 Norway
Erichsen
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.
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
22
The selection from the "Customers" table will now look like this:
90 Matti
Wilman Kala Keskuskatu 45 Helsinki 21240 Finland
Karttunen
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: It is very important to understand that 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!
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;
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
23
Demo Database
Assume we have the following "Persons" table:
Suppose that the "Address" column in the "Persons" table is optional. If a record is inserted with no
value for "Address", the "Address" column will be saved with a NULL value.
24
The SQL 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;
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!
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
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;
25
The selection from the "Customers" table will now look like this:
The following SQL statement will update the contactname to "Juan" for all records where country is
"Mexico":
Example
UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
The selection from the "Customers" table will now look like this:
26
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:
DELETE Syntax
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE
statement. The WHERE clause specifies which record(s) that should be deleted. If you omit the
WHERE clause, all records in the table will be deleted!
27
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
or:
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
Example
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
30
COUNT() Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID)
FROM Products;
AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
Demo Database
Below is a selection from the "OrderDetails" table in the Northwind sample database:
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
31
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 used in conjunction with the LIKE operator:
Note: MS Access uses a question mark (?) instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
32
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
The following SQL statement selects all customers with a CustomerName ending with "a":
Example
The following SQL statement selects all customers with a CustomerName that have "or" in any
position:
Example
The following SQL statement selects all customers with a CustomerName that have "r" in the
second position:
33
Example
The following SQL statement selects all customers with a CustomerName that starts with "a" and
are at least 3 characters in length:
Example
The following SQL statement selects all customers with a ContactName that starts with "a" and
ends with "o":
Example
The following SQL statement selects all customers with a CustomerName that does NOT start with
"a":
Example
Wildcard characters are used with 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 used in conjunction with the LIKE operator:
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
34
LIKE Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"
WHERE CustomerName LIKE '%a' Finds any values that ends 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 Finds any values that starts with "a" and are at least 3 characters in
'a_%_%' length
WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Christina
5 Berglunds snabbköp Berguvsvägen 8 Luleå S-958 22 Sweden
Berglund
Example
The following SQL statement selects all customers with a City containing the pattern "es":
35
Example
Example
The following SQL statement selects all customers with a City starting with "L", followed by any
character, followed by "n", followed by any character, followed by "on":
Example
Example
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
36
Using the [!charlist] Wildcard
The two following SQL statements selects all customers with a City NOT starting with "b", "s", or
"p":
Example
Or:
Example
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);
37
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" and
"UK":
Example
The following SQL statement selects all customers that are NOT located in "Germany", "France" or
"UK":
Example
The following SQL statement selects all customers that are from the same countries as the
suppliers:
Example
38
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
Below is a selection from the "Products" table in the Northwind sample database:
BETWEEN Example
The following SQL statement selects all products with a price BETWEEN 10 and 20:
Example
Example
39
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
Example
Example
Sample Table
Below is a selection from the "Orders" table in the Northwind sample database:
40
BETWEEN Dates Example
The following SQL statement selects all orders with an OrderDate BETWEEN '04-July-1996' and
'09-July-1996':
Example
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
SELECT column_name(s)
FROM table_name AS alias_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
41
And a selection from the "Orders" table:
Example
The following SQL statement creates two aliases, one for the CustomerName column and one for
the ContactName column. Note: It requires double quotation marks or square brackets 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
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the following:
42
Example
The following SQL statement is the same as above, but without aliases:
Example
43
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.
Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:
Example
44
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records
from the right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records
from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database.
45
SQL INNER JOIN Example
The following SQL statement selects all orders with customer information:
Example
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!
Example
Each SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
UNION Syntax
46
UNION ALL Syntax
The UNION operator selects only distinct values by default. To allow duplicate values, use UNION
ALL:
Note: The column names in the result-set are usually equal to the column names in the first
SELECT statement in the UNION.
Demo Database
In this tutorial we will use the well-known Northwind sample database.
47
SQL UNION Example
The following SQL statement selects all the different cities (only distinct values) from "Customers"
and "Suppliers":
Example
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!
Example
Example
48
SQL UNION ALL With WHERE
The following SQL statement selects all German cities (duplicate values also) from "Customers"
and "Suppliers":
Example
Example
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
49
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
The following SQL statement lists the number of customers in each country, sorted high to low:
Example
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
Example
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
51
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
Example
The following SQL statement lists the number of customers in each country, sorted high to low
(Only include countries with more than 5 customers):
Example
52
Demo Database
Below is a selection from the "Orders" table in the Northwind sample database:
Example
The following SQL statement lists if the employees "Davolio" or "Fuller" have registered more than
25 orders:
Example
53
The SQL EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns true if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
54
SQL EXISTS Examples
The following SQL statement returns TRUE and lists the suppliers with a product price less than
20:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE SupplierId =
Suppliers.supplierId AND Price < 20);
The following SQL statement returns TRUE and lists the suppliers with a product price equal to 22:
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE SupplierId =
Suppliers.supplierId AND Price = 22);
The ANY operator returns true if any of the subquery values meet the condition.
The ALL operator returns true if all of the subquery values meet the condition.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
ALL Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
55
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
The following SQL statement returns TRUE and lists the productnames if it finds ANY records in
the OrderDetails table that quantity = 10:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
The following SQL statement returns TRUE and lists the productnames if it finds ANY records in
the OrderDetails table that quantity > 99:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity > 99);
56
SQL ALL Example
The ALL operator returns TRUE if all of the subquery values meet the condition.
The following SQL statement returns TRUE and lists the productnames if ALL the records in the
OrderDetails table has quantity = 10:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);
57