Book SQL PDF
Book SQL PDF
Book SQL PDF
net/publication/319852714
CITATIONS READS
0 47,054
1 author:
Fernando Almeida
Global Humanistic University
91 PUBLICATIONS 186 CITATIONS
SEE PROFILE
Some of the authors of this publication are also working on these related projects:
All content following this page was uploaded by Fernando Almeida on 17 September 2017.
1/15/2016
Practical SQL Guide for Relational Databases 2016
Table of Contents
Acronyms....................................................................................................................................... 6
Glossary ......................................................................................................................................... 7
1. Introduction............................................................................................................................... 8
1.1 Contextualization ................................................................................................................ 8
1.2 Objectives ............................................................................................................................ 9
1.3 Book Structure..................................................................................................................... 9
5. Delete Data.............................................................................................................................. 19
Page 2
Practical SQL Guide for Relational Databases 2016
16. SQL Queries - Operator "Any" and "All"................................................................................ 41
Bibliography ................................................................................................................................ 54
Page 3
Practical SQL Guide for Relational Databases 2016
Index of Figures
Figure 1 - Contents of table Products ......................................................................................... 14
Figure 2 - Contents of table Customers ...................................................................................... 15
Figure 3 - Contents of table Orders ............................................................................................. 15
Figure 4 - Contents of table OrdersProducts .............................................................................. 16
Figure 5 - Contents of table Products after update .................................................................... 17
Figure 6 - Contents of table Orders after update........................................................................ 18
Figure 7 - Contents of table OrdersProducts after delete .......................................................... 19
Figure 8 - Contents of table OrdersProducts after delete .......................................................... 20
Figure 9 - Basic structure of SQL ................................................................................................. 22
Figure 10 - Contents of table Customer ...................................................................................... 22
Figure 11 - Contents of all fields in table Products ..................................................................... 23
Figure 12 - Information regarding orders and customers ........................................................... 23
Figure 13 - Information regarding three tables .......................................................................... 24
Figure 14 - Shows the calculation of marginStock ...................................................................... 24
Figure 15 - Shows the calculation of modResult ......................................................................... 25
Figure 16 - Shows all customers ending in "a" ............................................................................ 26
Figure 17 - Shows all customers fields which name contains "e" ............................................... 27
Figure 18 - Shows products which price is above average.......................................................... 28
Figure 19 - Shows all countries of customers ............................................................................. 29
Figure 20 - Shows the highest and average price ....................................................................... 29
Figure 21 - Shows the smallest and average price ...................................................................... 30
Figure 22 - Shows the total number of products, average price, highest price, smallest price
and total stock ............................................................................................................................. 30
Figure 23 - Displays the upper and lower names of the customers ........................................... 31
Figure 24 - Shows the size of the customers' name .................................................................... 32
Figure 25 - Shows 3 approaches to diplay the price of products ................................................ 32
Figure 26 - Counts the number of orders per customer ............................................................. 33
Figure 27 - Shows the quantity of itens and number of products per customer/order ............. 33
Figure 28 - Using the clause Having to filter results.................................................................... 34
Figure 29 - Order data per name of customer ............................................................................ 35
Figure 30 - Ordering name of customer by inverse order .......................................................... 35
Figure 31 - Returning top elements of a query ........................................................................... 36
Figure 32 - Structure of a sub-query ........................................................................................... 37
Page 4
Practical SQL Guide for Relational Databases 2016
Figure 33 - Shows the product with maximum price .................................................................. 37
Figure 34 - Shows the customer with max customer code and given delivery date .................. 38
Figure 35 - Shows the delivery date of orders that have specified quantity .............................. 38
Figure 36 - Basic approach using the "IN" operator.................................................................... 39
Figure 37 - Return all customer fields that have orders ............................................................. 40
Figure 38 - Shows customers that don't have orders ................................................................. 40
Figure 39 - Shows the use of ANY operator ................................................................................ 41
Figure 40 - Shows the use of ANY operator ................................................................................ 41
Figure 41 - Shows the use of ANY operator ................................................................................ 42
Figure 42 - Shows the use of ALL operator ................................................................................. 42
Figure 43 - Shows the use of UNION operator ............................................................................ 43
Figure 44 - Shows the use of UNION ALL operator ..................................................................... 44
Figure 45 - Shows the use of INTERSECT operator...................................................................... 44
Figure 46 - Shows the use of MINUS operator............................................................................ 45
Figure 47 - Structure of inner and natural joins .......................................................................... 46
Figure 48 - Shows the use of inner and natural joins .................................................................. 47
Figure 49 - Structure of Left Outer Join....................................................................................... 47
Figure 50 - Shows the use of Left Join ......................................................................................... 48
Figure 51 - Structure of Right Outer Join .................................................................................... 48
Figure 52 - Shows the use of Right Join....................................................................................... 49
Figure 53 - Structure of Full Outer Join ....................................................................................... 49
Figure 54 - Shows the use of Full Outer Join ............................................................................... 50
Figure 55 - Example of creating a view ....................................................................................... 51
Figure 56 - Get the date from system ......................................................................................... 52
Figure 57 - Get the user logged in system................................................................................... 53
Page 5
Practical SQL Guide for Relational Databases 2016
Acronyms
CLI - Command-Line Interface
I/O - Input/Output
ORA - Oracle
Page 6
Practical SQL Guide for Relational Databases 2016
Glossary
MySQL - MySQL is an open source relational database management system (RDBMS) based on
Structured Query Language (SQL).
SQL Server - SQL Server is a relational database management system (RDBMS) from Microsoft
that's designed for the enterprise environment.
Page 7
Practical SQL Guide for Relational Databases 2016
1. Introduction
1.1 Contextualization
SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to
communicate with a database. According to ANSI (American National Standards Institute), it is
the standard language for relational database management systems. SQL statements are used
to perform tasks such as update data on a database, or retrieve data from a database. Some
common relational database management systems that use SQL are: Oracle, Sybase, Microsoft
SQL Server, Access, Ingres, etc.
The SQL Standard has gone through a lot of changes during the years, which have added a
great deal of new functionality to the standard, such as support for XML, triggers, regular
expression matching, recursive queries, standardized sequences and much more.
The SQL language is based on several elements. For the convenience of SQL developers all
necessary language commands in the corresponding database management systems are
usually executed through a specific SQL command-line interface (CLI). These commands can be
grouped in the following areas:
Clauses - the clauses are components of the statements and the queries;
Expressions - the expressions can produce scalar values or tables, which consist of
columns and rows of data;
Predicates - they specify conditions, which are used to limit the effects of the
statements and the queries, or to change the program flow;
Statements - using statements user can control transactions, program flow, connections,
sessions, or diagnostics. In database systems the SQL statements are used for sending
queries from a client program to a server where the databases are stored. In response,
the server processes the SQL statements and returns to the client program. This allows
users to execute a wide range of fast data manipulation operations from simple data
inputs to more complex queries.
In order to guide students through the elementary syntax of SQL guide, a relational model is
presented below.
This proposed relational model is normalized in 3NF and it is composed by four tables, which
one identified by their primary keys (underlined) and the foreign keys are identified by "->"
symbol.
Page 8
Practical SQL Guide for Relational Databases 2016
The relational model describes generally a simple scenario of an ecommerce company that has
several products and customer. Each customer can create new orders that typically is
composed by several products.
1.2 Objectives
This mini books intends to provide a brief reference guide for undergraduate students that
intend to learn SQL in the context of their curricular units at university. The book presents the
main reference SQL syntax items (DDL and DML) and also presents the most important syntax
instructions that should be adopted in order to build relational databases in MySQL, SQL
Server or Oracle. This mini book doesn't intend to be a full SQL reference, but it only focus on
most critical aspects of the SQL syntax. The DCL syntax is not looked in the context of this
publication.
The scripts that will be shown in next chapters were testes using the following databases:
MySQL 5.6;
Chapter 1 "Introduction" - gives a brief overview about SQL language and organization
of the book;
Chapter 2 "Declaring Tables" - presents the syntax how to declare a new tables in
relational databases;
Chapter 3 "Insert Data" - presents the syntax in order to insert new data in a relational
database;
Chapter 4 "Update Data" - presents the syntax to update data previously stored in a
relational database;
Chapter 6 "Remove Tables" - presents the syntax to remove a table from a relational
database;
Chapter 7 "SQL Queries - Basic Structure" - shows the basic structure how a SQL query is
organized and structured;
Chapter 8 "SQL Queries - Comparing Strings" - shows how to compare string contents
using only SQL syntax;
Chapter 9 "SQL Queries - Aggregation Operators" - shows the most relevant aggregation
operators that are useful in SQL, such as AVG(), COUNT(), MAX(), MIN() and SUM();
Chapter 10 "SQL Queries - Scalar Functions" - presents the most useful scalar functions
that are available in SQL;
Page 9
Practical SQL Guide for Relational Databases 2016
Chapter 11 "SQL Queries - Grouping Elements" - presents the use of GROUP BY syntax in
SQL;
Chapter 12 "SQL Queries - Ordering Data" - presents the use of "ORDER BY" syntax in
SQL;
Chapter 13 "SQL Queries - Returning Top Elements" - presents an approach to return the
top elements of a SQL statement;
Chapter 14 "SQL Queries - Sub-queries" - shows the use of complex SQL queries
adopting a sub-query approach;
Chapter 15 "SQL Queries - Operator "IN" and "EXISTS" - shows the use of operator in and
exists and how to convert an "IN" into "EXISTS" approach;
Chapter 16 "SQL Queries - Operator "ANY" and "ALL" - shows the use of these two
clauses in conjunction with sub-queries;
Chapter 17 "SQL Queries - Operations with SETS" - shows the use of SQL in order to
perform operations with sets;
Chapter 18 "SQL Queries - Joins" - shows the use of different types of joins, namely inner
joins, left outer joins, right outer joins and full outer joins;
Chapter 19 "SQL Queries - Views" - shows the process of creating views in SQL and how
to invoke them;
Chapter 20 "SQL Queries - System Data" - shows the use of some system data operations
in order to get the system date and the logged user;
"Annex I - Script for MySQL Databases" - presents the full SQL script for a MySQL
database;
"Annex II - Script for MS SQL Server Databases" - presents the full SQL script for a MS
SQL Server database;
"Annex III - Script for Oracle Databases" - presents the full SQL script for an Oracle
database.
Page 10
Practical SQL Guide for Relational Databases 2016
2. Declaring Tables
The first step when creating a new database application is the process of declaring the tables.
In our example we have 4 tables to be created: Products, Orders, OrdersProducts and
Customer. We will start by the creation of the table Products.
The table Products records all the products that the company has in its catalogue. The script
for the creation of this table is given below. The same script can be used to MySQL, SQL Server
and Oracle DBMS.
Then, we will create the table Customers. Like in previous example the same script can be used
for all three databases (MySQL, SQL Server and Oracle).
Then, we will create the table Orders. Like before the script for both databases are the same.
Page 11
Practical SQL Guide for Relational Databases 2016
create table Orders
(
cod_order integer,
date_order date,
date_delivery date,
cod_customer integer,
CONSTRAINT Orders_pk PRIMARY KEY (cod_customer),
CONSTRAINT Orders_Cust_fk FOREIGN KEY (cod_customer)
REFERENCES Customers(cod_customer)
);
The primary key is the "cod_order". However, the Orders table also has a foreign key in the
field "cod_customer". The foreign key is connected to the primary key of the table "Customer"
by the field "cod_customer". It is also relevent to highlight the declaration of two variables of
the date type. The date format is represented by "YYYY-MM-DD" and its supported range is
from '1000-01-01' to '9999-12-31'.
Finally, the script for OrdersProducts is presented. Here the script below only works in MySQL
due to the int() type.
To make it work in SQL Server we need to change int() type for decimal(). The full corrected
script is given below.
Page 12
Practical SQL Guide for Relational Databases 2016
numbers of 2 digitals for the integer part.
Page 13
Practical SQL Guide for Relational Databases 2016
3. Insert Data
The insertion of new data in a database can be done by following two different, but similar,
approaches:
The first form does not specify the column names where the data will be inserted, only
their values;
The second form specifies both the column names and the values to be inserted.
The scripts to insert data are exactly the same for MySQL, SQL Server and Oracle databases.
For the introduction of data in tables "Products" and "Customers" we will adopt the second
approach.
After that the contents of the table "Products" are depicted in Figure 1.
Page 14
Practical SQL Guide for Relational Databases 2016
It is also presented in Figure 2 the contents of table "Customers".
In order to place new data in table "Orders" we will use the script below that gives data values
in all fields.
Finally, we will adopt the script below to include information regarding each order. This
information is stored in table "OrdersProducts".
Page 15
Practical SQL Guide for Relational Databases 2016
The Order with code "1" and "4" have two products; the Order with code "5" has three
products; the Order with code "3" has 4 products; finally the Order with code "2" has only one
product.
The contents of the table "OrdersProducts" after the execution of the above script is given in
Figure 4.
Page 16
Practical SQL Guide for Relational Databases 2016
4. Update Data
A very useful operation is update previous inserted data. The syntax to perform this operation
is the "Update Table". The syntax can be slight different in some situations like it will be
presented in next examples.
In the first situation we will update just one field considering the value of other field in the
same table.
Update Products
Set unit_price = 1.99
Where description = 'Eggs';
After the execution of this script the unit_price of eggs is 1.99€. The others fields of the tables
remains untouched.
Update Products
Set available_stock = 25, minimal_stock = 10
Where description = 'Eggs';
After the execution of this script the available stock and minimal stock of eggs will be changed
to 25 and 10, respectively.
In the third situation we will update again the price field, but this time for the soda product.
Update Products
Set unit_price = unit_price * 1.25
Where description = 'Soda';
After the execution of this script the unit price of soda product will be increased by 25%.
The contents of the table "Products" after the execution of all previous scripts is shown in
Figure 5.
Finally, in the fourth situation we will update the date delivery order of the Peter. For that, we
will need to use and access two tables: "Orders" and "Customers".
Update Orders
Set date_delivery = '2015-12-29'
Where Orders.cod_customer = (Select cod_customer
From Customers
Where name='Peter');
Page 17
Practical SQL Guide for Relational Databases 2016
After the execution of this script, the delivery date of all orders made by Peter will be 29th
December of 2015.
The above script doesn't work in MySQL databases. To make it work in MySQL we shall
perform a slight modification.
The contents of table "Orders" after the execution of previous scripts is shown in Figure 6.
Page 18
Practical SQL Guide for Relational Databases 2016
5. Delete Data
The delete instruction in SQL is used to delete data from a table. The most basic syntax is to
use this instruction to delete all data from a table. The syntax to perform this operation is
exactly the same for all databases (MySQL, SQL Server and Oracle).
If we want to delete a number of elements that accomplishes a given rule, we can add the
"Where" clause. We show here one example how to perform it involving only one table.
Now we will give two examples how to use the "Delete From..." operation using multiple
tables and sub-queries.
After the execution of the previous script the content of table "OrdersProducts" is presented in
Figure 8.
Page 19
Practical SQL Guide for Relational Databases 2016
If we want to delete all itens from OrdersProducts that its products has no content for the
description field we can adopt the approach below.
Finally SQL offers the "Truncate" command to removes all rows from a table. The operation
cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use
as much undo space as a DELETE, but it should be used carefully. We give an example below
how to use it.
It is important to highlight that DROP (that will be seen in next chapter) and TRUNCATE are
DDL commands, whereas DELETE is a DML command. As such, DELETE operations can be rolled
back (undone), while DROP and TRUNCATE operations cannot be rolled back.
Page 20
Practical SQL Guide for Relational Databases 2016
6. Remove Tables
Remove a table from a database is one of the easiest operations in SQL. However, it shouldn't
be mix with the instruction "delete from..." that deletes table. In order to remove a table from
a database we should use the "Drop Table..." command. This instruction works in all three
databases (MySQL, SQL Server and Oracle).
However, it would be totally possible to remove the "OrdersProducts" table from the system.
Page 21
Practical SQL Guide for Relational Databases 2016
Only the two initial clauses are mandatory ("Select" and "From"). The others elements are
optional.
One of the most used queries in SQL is to show all the contents of a table. It can be used liked
in the example below.
It is possible to choose only the fields to be shown, like in the example below.
The execution of the above script displays the content of Figure 10.
If we only want to show the distinct country of customers, we can use the instruction "distinct"
in Select clause, like it is shown below.
We can use also the "Where" clause to restrict the elements of a table that will be shown. An
example of this approach is shown below.
Page 22
Practical SQL Guide for Relational Databases 2016
Select *
From Products
Where Available_stock is not NULL;
This instruction shows all products that have stock in warehouse.
Select *
From Products
Where (Available_stock is NULL and unit_price > 1.00) or minimal_stock > 0;
This instruction shows all products which there is stock in warehouse and price is higher than
1€. It also includes in the result all field which defined minimal_stock is positive.
The execution of the above script shows the following result (Figure 11).
In the "From" clause we can use more than one table. We show this situation using two
examples.
Page 23
Practical SQL Guide for Relational Databases 2016
In the next example we use three tables in "From" clause.
The result of the execution of the above script is given in Figure 13.
Finally we demonstrate how to use SQL with some basic math operations. We start by using
the operator "-" in the example below.
The result of the execution of the above script is given in Figure 14.
In next example we use the modulo operation, which is responsible to find the remainder after
division of one number by another (sometimes called modulus).
Page 24
Practical SQL Guide for Relational Databases 2016
select cod_product, description, mod(available_stock, minimal_stock) as modResult
From Products;
This instruction calculates the module of division by available stock per minimal stock. It also
shows the code of product and description for all products.
The above script only works for MySQL and Oracle databases. To make it work in SQL Server
we must use the "%" operator, like it follows.
The result of the execution of the above script is given in Figure 15.
Page 25
Practical SQL Guide for Relational Databases 2016
In the first example we define a wildcard (missing letters) before the pattern.
In the second example we define a wildcard after the pattern. The statement is very similar to
previous.
In both situations the only record returned by the instruction is given in example below (Figure
16).
In the third example we define a simultaneous wildcard after and before the pattern.
Page 26
Practical SQL Guide for Relational Databases 2016
Page 27
Practical SQL Guide for Relational Databases 2016
If we want to show the price with only two decimal places, we must slight change the previous
statement.
Page 28
Practical SQL Guide for Relational Databases 2016
Select Count(*) From Customers;
This instruction returns the number of records in Customers table.
The second example uses simultaneously Count() function and distinct statement.
In second example we will return simultaneously the maximum and average values.
In second example we will return simultaneously the maximum and average values.
Page 29
Practical SQL Guide for Relational Databases 2016
SELECT MIN(unit_price) AS SmallestPrice, AVG(unit_price) AS AveragePrice
FROM Products;
This instruction returns the smallest unit price and the average price of all products.
Figure 22 - Shows the total number of products, average price, highest price, smallest price and total stock
Page 30
Practical SQL Guide for Relational Databases 2016
In the first example we will use simultaneously UCASE() and LCASE() functions. However, there
is an additional issue, because we must use a different statement for each specific database.
We will starting by presenting the statement for MySQL.
The statement for SQL Server and Oracle can be the same.
In the second example we use the LEN() function to return the size of a text field. This function
can only be used in a SQL Server database.
In MySQL and Oracle databases we must replace the "LEN()" function by the "LENGTH()"
function.
Page 31
Practical SQL Guide for Relational Databases 2016
Select name, LENGTH(name) as SizeName
from Customers;
This instruction shows all the customers' name and for each name presents its size.
In the third example we use the round() function. The following statement works well for the
three databases.
Page 32
Practical SQL Guide for Relational Databases 2016
The "Group By..." statement is used in conjunction with the aggregate functions to group the
result-set by one or more columns. Here we give 2 examples using the Group By statement.
The second example gives a more complex exercise with more than one table.
Figure 27 - Shows the quantity of itens and number of products per customer/order
In the last example we use the "Having..." clause to restrict the number of shown elements.
The "Having" clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.
Page 33
Practical SQL Guide for Relational Databases 2016
Select O.cod_customer, O.cod_order, sum(quantity), count(cod_product)
From Orders O, OrdersProducts OP
Where O.COD_ORDER = OP.COD_ORDER
Group By O.cod_customer, O.cod_order
Having sum(quantity) > 10;
This instruction is very similar to previous and it only adds an additional last line. The "Having"
clause only shows lines where the sum of quantity is higher than 10.
Page 34
Practical SQL Guide for Relational Databases 2016
Select *
From Customers
Order By Name;
This instruction selects all columns of Customers table ordering the records by name
(ascending order).
In second example we use the same Order By operation but now using the inverse order.
Select *
From Customers
Order By Name DESC;
This instruction selects all columns of Customers table ordering the records by name
(descending order).
Page 35
Practical SQL Guide for Relational Databases 2016
SELECT *
FROM Customers
Order By Name
Limit 3;
This instruction shows all fields of Customers table ordered by name. However, it only shows
the first three records.
In SQL Server it is possible to perform this operation using the syntax below.
SELECT Top 3 *
FROM Customers
Order By Name;
This instruction shows all fields of Customers table ordered by name. However, it only shows
the first three records.
Finally, in Oracle the same operation can be done using the syntax below.
SELECT *
FROM Customers
Where RowNum <= 3
Order By Name;
This instruction shows all fields of Customers table ordered by name. However, it only shows
the first three records.
Page 36
Practical SQL Guide for Relational Databases 2016
A SELECT clause;
A FROM clause;
A WHERE clause.
Typically a sub-query is usually added within the WHERE clause of another SQL SELECT
statement. The syntax model is depicted in Figure 32.
The sub-query (inner query) executes once before the main query (outer query) executes.
Consequently, the main query (outer query) uses the sub-query result.
In the first example we use always the same table in the inner and outer query.
Select description
From Products
Where unit_price = (Select max(unit_price)
From Products);
This instruction presents the description of the product which has the maximum unit price.
In the second example we use a sub-query that uses another table different from the outer
statement.
Page 37
Practical SQL Guide for Relational Databases 2016
Select name
From Customers
Where cod_customer = (Select max(distinct cod_customer)
From Orders
Where date_delivery >= '2015-12-26');
This instruction presents the name of customer which code of customer is maximum (most
recent) and has an order which date of delivery is equal or more recent than 26th December
2015.
Figure 34 - Shows the customer with max customer code and given delivery date
In the last example we use a sub-query that uses also another table different from the outer
statement.
Select date_delivery
From Orders
Where cod_order = (Select max(cod_order)
From OrdersProducts
Where quantity > 3);
This instruction presents the delivery date of the last order saved in the database that has an
item quantity higher than 3.
Figure 35 - Shows the delivery date of orders that have specified quantity
Page 38
Practical SQL Guide for Relational Databases 2016
In the first example we will use "IN" operator to check numeric values.
SELECT *
FROM Orders
WHERE cod_order IN (1, 3, 5);
This operation shows all fields of records in table Orders with order code equal to "1" or "3" or
"5".
In the second example we will use "IN" operator to check string values.
SELECT *
FROM Customers
WHERE name IN ('Peter', 'Elena');
This operation shows all fields of records in table Customers with name equal to "Peter" or
"Elena".
The operator "IN" can also be used with sub-queries. One example of this situation is given
below.
SELECT *
FROM Customers
WHERE cod_customer IN (SELECT cod_customer
From Orders);
This operation shows all customers that already have orders in the table. The operator "IN" is
used to retrieve several values from Orders table.
Page 39
Practical SQL Guide for Relational Databases 2016
The operators "IN" and "EXISTS" offer similar functionality, but the syntax is slight different.
The EXISTS checks the existence of a result of a sub-query. The EXISTS sub-query tests whether
a sub-query fetches at least one row. When no data is returned then this operator returns
'FALSE'.
In order to demonstrate the use of "EXISTS" operator we use the same previous example, but
now using "EXISTS" instead of "IN".
SELECT *
FROM Customers C
WHERE EXISTS (SELECT cod_customer
FROM Orders O
WHERE C.cod_customer = O.cod_customer);
This operation shows all customers that already have orders in the table. The operator
"EXISTS" is used to retrieve the customers code of all customers that have orders.
Both operators "IN" and "EXISTS" can be used with the prefix "NOT". An example of such
situation is given below.
Page 40
Practical SQL Guide for Relational Databases 2016
The operator "ANY" compares a value to each value in a list or results from a query and
evaluates to true if the result of an inner query contains at least one row. A simple example
using the "ANY" operator is given below.
SELECT description
FROM Products
WHERE cod_product = ANY
(SELECT cod_product
FROM OrdersProducts
WHERE Quantity = 1)
This instruction shows the description of the products that has a quantity order equal to 1.
Below it is a given another example using the same "ANY" operator, but changing the
comparing operator to ">=".
Page 41
Practical SQL Guide for Relational Databases 2016
Select name, address
From Customers
Where cod_customer < ANY (Select cod_customer From Orders);
This instruction shows name and address of customers which code of customer is below than
any code of customer that has already orders.
The ALL is used to select all records of a SELECT statement. It compares a value to every value
in a list or results from a query. The ALL must be preceded by the comparison operators and
evaluates to TRUE if the query returns no rows. Below it is a given an example.
Page 42
Practical SQL Guide for Relational Databases 2016
Union - the relation containing all tuples that appear in R1, R2, or both;
Intersect - is the relation containing all tuples that appear in both R1 and R2;
Difference - the relation containing all tuples of R1 that do not appear in R2.
The UNION operator is used to combine the result-set of two or more SELECT statements. The
SELECT statement within the UNION must have the same number of columns and have similar
or compatible data types.
Select description
From Products
Where cod_product > 3
UNION
Select description
From Products
Where cod_product > 1;
This instruction shows the description of all products which product code is higher than 3 or
higher than 1. The UNION statement let join the results of both SQL statements.
The UNION operator selects only distinct values by default. To allow duplicate values, use the
ALL keyword with UNION. An example of such situation is given below.
Select description
From Products
Where cod_product > 3
UNION ALL
Select description
From Products
Where cod_product > 1;
This instruction shows the description of all products which product code is higher than 3 or
higher than 1. However, and comparing to previous example, the records returned by both
queries are duplicated.
Page 43
Practical SQL Guide for Relational Databases 2016
The result of this operation is shown in Figure 44.
The SQL INTERSECT operator is used to return the results of 2 or more SELECT statements.
However, it only returns the rows selected by all queries or data sets. If a record exists in one
query and not in the other, it will be omitted from the INTERSECT results. An example of such
situation is given below. The script below only works in SQL Server and Oracle databases.
Select description
From Products
Where cod_product > 3
INTERSECT
Select description
From Products
Where cod_product > 1;
This instruction shows the description of all products which product code is higher than 3 or
higher than 1. However, and comparing to previous example, the records returned by both
queries are duplicated.
The INTERSECT operator isn't supported in MySQL. To make a similar function in MySQL we
can use the "IN", "EXISTS" or arithmetic operators. In our previous example we can reach the
same functionality by using simple arithmetic operators. An example of this approach is given
below.
Page 44
Practical SQL Guide for Relational Databases 2016
Select description
From Products
Where cod_product > 3 and cod_product > 1;
This instruction shows the description of all products which product code is higher than 3 or
higher than 1. It uses only arithmetic and boolean operations.
The SQL MINUS clause is used to combine two SELECT statements and returns rows from the
first SELECT statement that are not returned by the second SELECT statement. An example of
this situation is given below. This script only works in Oracle.
Select description
From Products
Where cod_product > 1
MINUS
Select description
From Products
Where cod_product > 3;
This instruction shows the description of all products that have a product code higher than 1
but below or equal to 3.
To make the previous script working in SQL Server we must use the clause "EXCEPT".
Select description
From Products
Where cod_product > 1
EXCEPT
Select description
From Products
Where cod_product > 3;
This instruction shows the description of all products that have a product code higher than 1
but below or equal to 3.
To make the script work in MySQL we must adopt a similar approach like we did in
"INTERSECT" clause. An example of this approach is given below.
Select description
From Products
Where cod_product > 1 and cod_product <= 3;
This instruction shows the description of all products that have a product code higher than 1
but below or equal to 3.
Page 45
Practical SQL Guide for Relational Databases 2016
Inner join and natural joins - select records that have matching values in both tables;
Left Outer Join - select records from the first (left-most) table with matching right table
records;
Right Outer Join - select record from the second (right-most) table with matching left
table records;
Full Outer Join - selects all records that match either left or right table records.
Instead of INNER JOIN we could be used the NATURAL JOIN clause, because the field name of
both tables is the same. Then, using the NATURAL JOIN syntax we get the following script.
The above script only works for MySQL and Oracle databases. The SQL Server database doesn't
support the NATURAL JOIN clause. Instead of NATURAL JOIN we can easily use the INNER JOIN
as used previously.
Page 46
Practical SQL Guide for Relational Databases 2016
The result of the execution of the two above scripts is displayed in Figure 48.
Page 47
Practical SQL Guide for Relational Databases 2016
Page 48
Practical SQL Guide for Relational Databases 2016
The above script works well for Oracle and SQL Server databases. However, we don't have
FULL JOINS on MySQL, but we can sure emulate them. Attending the above example we can do
that in MySQL by adopted the approach below.
Page 49
Practical SQL Guide for Relational Databases 2016
This instruction shows all customers' name and the code of orders simultaneously for all
customers and orders. In order to emulate the functionality of FULL OUTER JOIN we use both
LEFT and RIGHT joins.
Page 50
Practical SQL Guide for Relational Databases 2016
If we want to show the content of a view we can use the following syntax.
The result of this operation is empty due to the fact that there isn't any product which stock is
below the minimal stock.
The result after invoking the above view is given in Figure 55.
Page 51
Practical SQL Guide for Relational Databases 2016
The same operation can be done in SQL Server using the approach below.
Finally, in Oracle we must invoke the DUAL table. It is a table automatically created by Oracle
Database along with the data dictionary. Selecting from the DUAL table is useful for computing
a constant expression with the SELECT statement. Because DUAL has only one row, the
constant is returned only once.
SELECT TO_CHAR
(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "NOW"
FROM DUAL;
This instruction returns the current date and time.
The result of three previous operations are the same and is depicted in Figure 56.
Other common operation is to get the current logged user in the database. This operation has
also different SQL statements for each database. In MySQL this operation can be done as
follows.
The same operation can be done in SQL Server using the approach below. In SQL Server
"current user" is seen as a property and not a method.
Finally, the same operation in Oracle is given below. Like before we need to invoke the DUAL
table.
Page 52
Practical SQL Guide for Relational Databases 2016
select user from dual;
This instruction returns the current authenticated user.
Page 53
Practical SQL Guide for Relational Databases 2016
Bibliography
Database SQL Developer Supplementary Information for Microsoft SQL Server Migrations.
(n.d.). Retrieved 01 11, 2016, from
https://docs.oracle.com/cd/E10405_01/appdev.120/e10379/ss_oracle_compared.htm
Intro to SQL: Querying and managing data. (n.d.). Retrieved 12 21, 2015, from
https://www.khanacademy.org/computing/computer-programming/sql
Selecting from the DUAL Table. (n.d.). Retrieved 7 12, 2016, from
https://docs.oracle.com/cd/B19306_01/server.102/b14200/queries009.htm
Page 54
Practical SQL Guide for Relational Databases 2016
Page 55
Practical SQL Guide for Relational Databases 2016
Insert Into Customers (cod_customer, name)
Values (2, 'Peter');
Insert Into Customers (cod_customer, name)
Values (3, 'Elena');
Insert Into Customers (cod_customer, name)
Values (4, 'Shirley');
Insert Into Customers (cod_customer, name)
Values (5, 'John');
Update Products
Set available_stock = 25, minimal_stock = 10
Where description = 'Eggs';
Update Products
Set unit_price = unit_price * 1.25
Where description = 'Soda';
Page 56
Practical SQL Guide for Relational Databases 2016
/* SQL Queries - Basic Structure */
Select * From Customers;
Select *
From Products
Where (Available_stock is NULL and unit_price > 1.00) or minimal_stock > 0;
Page 57
Practical SQL Guide for Relational Databases 2016
SELECT MIN(unit_price) AS SmallestPrice FROM Products;
Select *
From Customers
Order By Name DESC;
Page 58
Practical SQL Guide for Relational Databases 2016
From Products);
Select name
From Customers
Where cod_customer = (Select max(distinct cod_customer)
From Orders
Where date_delivery >= '2015-12-26');
Select date_delivery
From Orders
Where cod_order = (Select max(cod_order)
From OrdersProducts
Where quantity > 3);
SELECT *
FROM Customers
WHERE name IN ('Peter', 'Elena');
SELECT *
FROM Customers
WHERE cod_customer IN (SELECT cod_customer
From Orders);
SELECT *
FROM Customers C
WHERE EXISTS ( SELECT cod_customer
FROM Orders O
WHERE C.cod_customer = O.cod_customer);
Page 59
Practical SQL Guide for Relational Databases 2016
Select description
From Products
Where cod_product > 3
UNION ALL
Select description
From Products
Where cod_product > 1;
Select description
From Products
Where cod_product > 3 and cod_product > 1;
Select description
From Products
Where cod_product > 1 and cod_product <= 3;
Page 60
Practical SQL Guide for Relational Databases 2016
Where available_stock < minimal_stock
Page 61
Practical SQL Guide for Relational Databases 2016
Page 62
Practical SQL Guide for Relational Databases 2016
Insert Into Customers (cod_customer, name)
Values (2, 'Peter');
Insert Into Customers (cod_customer, name)
Values (3, 'Elena');
Insert Into Customers (cod_customer, name)
Values (4, 'Shirley');
Insert Into Customers (cod_customer, name)
Values (5, 'John');
Update Products
Set available_stock = 25, minimal_stock = 10
Where description = 'Eggs';
Update Products
Set unit_price = unit_price * 1.25
Where description = 'Soda';
Update Orders
Set date_delivery = '2015-12-29'
Where Orders.cod_customer = (Select cod_customer From Customers Where name='Peter');
Page 63
Practical SQL Guide for Relational Databases 2016
/* SQL Queries - Basic Structure */
Select * From Customers;
Select *
From Products
Where (Available_stock is NULL and unit_price > 1.00) or minimal_stock > 0;
Page 64
Practical SQL Guide for Relational Databases 2016
SELECT MIN(unit_price) AS SmallestPrice FROM Products;
Select *
From Customers
Order By Name DESC;
Page 65
Practical SQL Guide for Relational Databases 2016
Select name
From Customers
Where cod_customer = (Select max(distinct cod_customer)
From Orders
Where date_delivery >= '2015-12-26');
Select date_delivery
From Orders
Where cod_order = (Select max(cod_order)
From OrdersProducts
Where quantity > 3);
SELECT *
FROM Customers
WHERE name IN ('Peter', 'Elena');
SELECT *
FROM Customers
WHERE cod_customer IN (SELECT cod_customer
From Orders);
SELECT *
FROM Customers C
WHERE EXISTS ( SELECT cod_customer
FROM Orders O
WHERE C.cod_customer = O.cod_customer);
Page 66
Practical SQL Guide for Relational Databases 2016
/* SQL Queries - Operations with Sets */
Select description
From Products
Where cod_product > 3
UNION
Select description
From Products
Where cod_product > 1;
Select description
From Products
Where cod_product > 3
UNION ALL
Select description
From Products
Where cod_product > 1;
Select description
From Products
Where cod_product > 3
INTERSECT
Select description
From Products
Where cod_product > 1;
Select description
From Products
Where cod_product > 1
EXCEPT
Select description
From Products
Where cod_product > 3;
Page 67
Practical SQL Guide for Relational Databases 2016
From products
Where available_stock < minimal_stock
Page 68
Practical SQL Guide for Relational Databases 2016
Page 69
Practical SQL Guide for Relational Databases 2016
Insert Into Customers (cod_customer, name)
Values (2, 'Peter');
Insert Into Customers (cod_customer, name)
Values (3, 'Elena');
Insert Into Customers (cod_customer, name)
Values (4, 'Shirley');
Insert Into Customers (cod_customer, name)
Values (5, 'John');
Update Products
Set available_stock = 25, minimal_stock = 10
Where description = 'Eggs';
Update Products
Set unit_price = unit_price * 1.25
Where description = 'Soda';
Update Orders
Set date_delivery = '2015-12-29'
Where Orders.cod_customer = (Select cod_customer From Customers Where name='Peter');
Page 70
Practical SQL Guide for Relational Databases 2016
/* SQL Queries - Basic Structure */
Select * From Customers;
Select *
From Products
Where (Available_stock is NULL and unit_price > 1.00) or minimal_stock > 0;
Page 71
Practical SQL Guide for Relational Databases 2016
SELECT MIN(unit_price) AS SmallestPrice FROM Products;
Select *
From Customers
Order By Name DESC;
Page 72
Practical SQL Guide for Relational Databases 2016
From Products);
Select name
From Customers
Where cod_customer = (Select max(distinct cod_customer)
From Orders
Where date_delivery >= '2015-12-26');
Select date_delivery
From Orders
Where cod_order = (Select max(cod_order)
From OrdersProducts
Where quantity > 3);
SELECT *
FROM Customers
WHERE name IN ('Peter', 'Elena');
SELECT *
FROM Customers
WHERE cod_customer IN (SELECT cod_customer
From Orders);
SELECT *
FROM Customers C
WHERE EXISTS (SELECT cod_customer
FROM Orders O
WHERE C.cod_customer = O.cod_customer);
Page 73
Practical SQL Guide for Relational Databases 2016
Select description
From Products
Where cod_product > 3
UNION ALL
Select description
From Products
Where cod_product > 1;
Select description
From Products
Where cod_product > 3
INTERSECT
Select description
From Products
Where cod_product > 1;
Select description
From Products
Where cod_product > 1
MINUS
Select description
From Products
Where cod_product > 3;
Page 74
Practical SQL Guide for Relational Databases 2016
ORDER BY C.Name;
Page 75