You are on page 1of 25

Topic 3.

DML SQL Language

HNEU,
Department of Information Systems,
Course Database,
V. V. Fedko
Contents
1. Data input
2. Data delete
3. Data change
4. Data retrieval
5. Join
6. Aggregate functions
7. Grouping results
8. Subqueries
9. Predicates with subqueries

HNEU, Department of Information Systems, Course Database, V. V. Fedko 2


Test questions
En: Ru:
1. Compare DDL and DML command 1. Сравните назначение команд DDL и DML
assignment 2. Запишите операторы добавления трех
2. Write down the operators for adding three строк в таблицу Производители
rows to the Manufacturers table (Код_проиводителя, Название, Адрес,
(ManufacturerId, Name, Address, Телефон)
Telephone). 3. Выведите дату, название производителя,
3. Display the date, name of the название товара и стоимость проданных
manufacturer, name of the product and товаров за 01.09.2019 и 02.09.2019,
cost of the product sold on 09.01.2019 используя таблицы
and 09.02.2019, using the table Товары(Код_товара, Наименование, Цена),
Products(ProductId, Name, Price, …), Производители(Код_производителя,
Manufacturers(ManufacturerId, Name, …), Наименование, …),
Продажи(Код_продажи, Дата_продажи,
Sales(SaleId, Sale_date, ProductId, Код_производителя, Код_товара,
ManufacturerId, Quantity). Количество).
Send your answers at email Name the Word file according to the template
TN_Surname_specialty_group, for example, T3_Johnson_121.019_1.
fvv.stud@gmail.com HNEU, Department of Information Systems, Course Database, V. V. Fedko 3
1. Data input
Data change queries:
• INSERT - add query;
• DELETE - delete query;
• UPDATE - update query.
All operations are performed with a
set of rows in the table.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 4


Query for data entry

INSERT INTO <table_name> [(column_name [, ... n])]


{VALUES (value [, ... n]) | <SELECT_operator>}

INSERT INTO Products (Name, Price, Purchase_price) INSERT INTO Products


VALUES (N'Bread "Rye"', 12.50, 10.32) VALUES (N'Bread "Rye"', 12.50, 10.32)

INSERT INTO Products SET IDENTITY_INSERT Products ON;


VALUES INSERT INTO Products(ProductId, Name, Price, Purchase_price)
(N'Bread "Ukrainian"', 13.50, 12.00), VALUES
(N‘Long loaf "Milk"', 12.80, 12.50), (11, N'Bread "Ukrainian"', 13.50, 12.00),
(N'Bun with poppy seeds', 10, 9) (12, N'Baton "Milk"', 12.80, 12.50),
(13, N'Bun with poppy seeds', 10, 9)

HNEU, Department of Information Systems, Course Database, V. V. Fedko 5


Copy rows

INSERT INTO <table_name> [(column_name [, ... n])]


<SELECT_operator>

Note. The target table must be created in advance.

Products ExpensiveProducts

INSERT INTO ExpensiveProducts


SELECT Name, Price
FROM Products
WHERE Price > 10

HNEU, Department of Information Systems, Course Database, V. V. Fedko 6


2. Data delete
Row group delete query
DELETE DELETE
FROM table_name FROM Products
[WHERE condition] WHERE Price > 10

HNEU, Department of Information Systems, Course Database, V. V. Fedko 7


3. Data change
Query to change the values ​in the row group
UPDATE table_name
SET column_name = new_value […, column_name = new_value]
[WHERE condition]

UPDATE Manufacturers
SET Web_site='www.oleksiivka.kh.ua'
WHERE (Name = N'Alekseevsky bakery')

HNEU, Department of Information Systems, Course Database, V. V. Fedko 8


4. Data retrieve
SELECT statement syntax
SELECT [ALL | DISTINCT] {* | [column_name [AS new_name]]} [, ... n]
FROM table_name [[AS] nickname] [, ... n]
[WHERE <condition>]
[GROUP BY column_name [, ... n]]
[HAVING <group_selection_criteria>]
[ORDER BY column_name [ASC | DESC] [, ... n]]

HNEU, Department of Information Systems, Course Database, V. V. Fedko 9


1. Select all columns 2. Select some columns 3. Selecting rows without duplicates
SELECT * SELECT Name, Price SELECT DISTINCT Price
FROM Products FROM Products FROM Products

4. Selecting with renaming columns


SELECT Name AS "Product name", Price AS "Sale price“
FROM Products

5. Calculated columns in query


SELECT Name, Price-Purchase_price AS Markup
FROM Products
6. Using character strings in queries
SELECT Name, Price, N'грн.' AS Currency
FROM Products

HNEU, Department of Information Systems, Course Database, V. V. Fedko 10


7. Conditional expressions using comparisons
SELECT Name, Price
FROM Products
WHERE Price > 10

8. Conditional expressions using the range 9. Conditional expressions using the range
SELECT Name, Price SELECT Name, Price
FROM Products FROM Products
WHERE (Price >= 10) AND (Price <=13) WHERE Price Between 10 AND 13

10. Conditional expressions using a set


SELECT ProductId, Name
FROM Products
WHERE ProductId in (1, 3, 4)

HNEU, Department of Information Systems, Course Database, V. V. Fedko 11


11. Conditional expressions using a template 12. Conditional expressions using a template
SELECT Name, Price SELECT Name, Price
FROM Products FROM Products
WHERE Name LIKE 'Bun%' WHERE Name LIKE '%with%'

13. Conditional expressions using the value Null 14. Conditional expressions using the value NOT Null

SELECT ProductId, Name SELECT ProductId, Name


FROM Products FROM Products
WHERE Price IS NULL WHERE Price IS NOT NULL

15. Sorting 16. Sorting 17. Sorting

SELECT Name, Price SELECT Name, Price SELECT Name, Price


FROM Products FROM Products FROM Products
ORDER BY Price DESC ORDER BY Name ASC ORDER BY Name

HNEU, Department of Information Systems, Course Database, V. V. Fedko 12


5. Join
Purpose
Used to combine columns from two tables in the results table

The row pairs that make up the joined table are those where the
matching columns in each of the two tables have the same value.

Where
SELECT Sale_date, Name, Quantity
FROM Sales, Products
WHERE (Sales.ProductId = Products.ProductId)

HNEU, Department of Information Systems, Course Database, V. V. Fedko 13


Where
SELECT Sale_date, Name, Quantity
FROM Sales, Products
WHERE (Sales.ProductId = Products.ProductId)

SALE_ID SALE_DATE PRODUCT_ID MANUFACTURER_ID QUANTITY


1 01.09.2019 1 1 200
2 01.09.2019 2 1 250
3 01.09.2019 3 1 180
PRODUCT_ID NAME PRICE PURCHASE_PRICE
4 01.09.2019 1 2 220
1 Bread "Ukrainian" 13.50 12.00
5 02.09.2019 1 1 200
2 Baton "Milk" 12.80 12.50
6 02.09.2019 2 2 180
3 Bun with poppy seeds 10 9
SALE_DATE NAME QUANTITY
01.09.2019 Bread "Ukrainian" 200
01.09.2019 Baton "Milk" 250
01.09.2019 Bun with poppy seeds 180
01.09.2019 Bread "Ukrainian" 220
02.09.2019 Bread "Ukrainian" 200
02.09.2019 Baton "Milk" HNEU, Department of Information
180 Systems, Course Database, V. V. Fedko 14
JOIN
Syntax
FROM first_table join_type second_table ON join_condition

JOIN

SELECT Sale_date, Name, Quantity


FROM Sales JOIN Products ON Sales.ProductId = Products.ProductId

JOIN (nicknames)

SELECT Sale_date, Name, Quantity


FROM Sales AS s JOIN Products AS p ON s.ProductId = p.ProductId

HNEU, Department of Information Systems, Course Database, V. V. Fedko 15


Join types

[INNER] JOIN - returns rows that have matching values in both tables
LEFT [OUTER] JOIN - returns all rows from the left table, and the matched rows from
the right table
RIGHT [OUTER] JOIN – returns all rows from the right table, and the matched rows
from the left table
FULL [OUTER] JOIN - returns all rows when there is a match in either left or right table

HNEU, Department of Information Systems, Course Database, V. V. Fedko 16


As a result, we have all the possible
combinations of rows from both tables.
Cartesian product
SELECT Sale_date, Name, Quantity
FROM Sales, Products

CROSS JOIN
SELECT Sale_date, Name, Quantity
FROM Sales CROSS JOIN Products

HNEU, Department of Information Systems, Course Database, V. V. Fedko 17


6. Aggregate functions
Purpose
COUNT – returns the number of values in a specified column
SUM – returns the sum of the values in a specified column
AVG – returns the average of the values in a specified column
MIN – returns the smallest value in a specified column
MAX – returns the largest value in a specified column
MIN, MAX, AVG COUNT
SELECT MIN (Price) AS "Minimal price", SELECT COUNT(*) AS "Number of products“
MAX (Price) AS "Maximal price", FROM Products
AVG (Price) AS "Average price"
FROM Products

HNEU, Department of Information Systems, Course Database, V. V. Fedko 18


7. Grouping results
Purpose
Selected rows are collected in groups. Each group consists of rows with the same
values of the specified field (GROUP BY field).
Rows of each group are performed using aggregate functions.
As a result, only one row from each group and the calculated values are displayed.
In SELECT clause, there are only grouping fields and aggregate functions.

GROUP BY
SELECT Sale_date, SUM (Quantity*Price) AS "Cost“
FROM Sales JOIN Products ON Sales.ProductId = Products.ProductId
WHERE (ManufacturerId=1)
GROUP BY Sale_date

HNEU, Department of Information Systems, Course Database, V. V. Fedko 19


HAVING
SELECT Sale_date, SUM (Quantity*Price) AS "Cost“
FROM Sales JOIN Products ON Sales.ProductId = Products.ProductId
WHERE (ManufacturerId=1)
GROUP BY Sale_date
HAVING SUM(Quantity*Price) > 5000

HAVING vs WHERE
HAVING selects from the resulting dataset groups with the results of aggregated values;
WHERE selects for the calculation of aggregate values by grouping rows (excluded from
calculations rows that do not satisfy the condition);
in the WHERE search condition you cannot specify aggregate functions.

HNEU, Department of Information Systems, Course Database, V. V. Fedko 20


8. Subqueries
Definition: Subquery is a nested SELECT statement in another SELECT statement.
Using:
• The results of this inner SELECT statement (or subselect) are used in the outer
statement to help determine the contents of the final result.
• A subselect can be used in the WHERE and HAVING clauses of an outer SELECT
statement, where it is called a subquery or nested query.
• Subselects may also appear in INSERT, UPDATE, and DELETE statements

Types of subquery:
A scalar subquery - returns a single column and a single row, that is, a single value.
A row subquery - returns multiple columns, but only a single row.
A table subquery - returns one or more columns and multiple rows.
HNEU, Department of Information Systems, Course Database, V. V. Fedko 21
1. Scalar subquery 3. Table subquery
SELECT Name, Price SET LANGUAGE RUSSIAN;
FROM Products SELECT Name
WHERE Price = ( FROM Products
SELECT MAX(Price) WHERE (ProductId IN (
FROM Products SELECT ProductId
) FROM Sales
WHERE Sale_date='2.09.2021')
)
2. Row subquery
SELECT Sale_date, (SELECT Name
FROM Products
WHERE ProductId = Sales.ProductId
) AS Product
FROM Sales

HNEU, Department of Information Systems, Course Database, V. V. Fedko 22


9. Predicates with subqueries
ALL, ANY ALL (max Price)

ALL - the condition will be true only if it SELECT Name, Price


is satisfied by all values produced by the FROM Products
subquery. WHERE Price >=
ANY - the condition will be true if it is ALL(SELECT Price
satisfied by any (one or more) values FROM Products)
produced by the subquery.
ANY
If the subquery is empty,
the ALL condition returns true, SELECT DISTINCT Sale_date
the ANY condition returns false. FROM Sales
WHERE ManufacturerId =
ANY(SELECT ManufacturerId
FROM Manufacturers
WHERE Address Like '%Kharkiv%')
HNEU, Department of Information Systems, Course Database, V. V. Fedko 23
EXISTS, NOT EXISTS
EXISTS is true if and only if there exists at least one row in the result table returned by the
subquery; it is false if the subquery returns an empty result table.
NOT EXISTS is the opposite of EXISTS.
Because EXISTS and NOT EXISTS check only for the existence or nonexistence of rows in the
subquery result table, the subquery can contain any number of columns.

EXISTS
SELECT Name
FROM Products
WHERE EXISTS (SELECT *
FROM Sales
WHERE Products.ProductId = Sales.ProductId)

HNEU, Department of Information Systems, Course Database, V. V. Fedko 24


Test questions
En: Ru:
1. Compare DDL and DML command 1. Сравните назначение команд DDL и DML
assignment 2. Запишите операторы добавления трех
2. Write down the operators for adding three строк в таблицу Производители
rows to the Manufacturers table (Код_проиводителя, Название, Адрес,
(ManufacturerId, Name, Address, Телефон)
Telephone). 3. Выведите дату, название производителя,
3. Display the date, name of the название товара и стоимость проданных
manufacturer, name of the product and товаров за 01.09.2019 и 02.09.2019,
cost of the product sold on 09.01.2019 используя таблицы
and 09.02.2019, using the table Товары(Код_товара, Наименование, Цена),
Products(ProductId, Name, Price, …), Производители(Код_производителя,
Manufacturers(ManufacturerId, Name, …), Наименование, …),
Продажи(Код_продажи, Дата_продажи,
Sales(SaleId, Sale_date, ProductId, Код_производителя, Код_товара,
ManufacturerId, Quantity). Количество).
Send your answers at email Name the Word file according to the template
TN_Surname_specialty_group, for example, T3_Johnson_121.019_1.
fvv.stud@gmail.com HNEU, Department of Information Systems, Course Database, V. V. Fedko 25

You might also like