Topic 2.
General characteristics of linguistic
means of communication
with DBMS.
DDL SQL Language
HNEU,
Department of Information Systems,
Course Database,
V. V. Fedko
Contents
1. Language communication with DBMS
2. SQL DDL Language.
3. DDL commands for create tables.
4. Modifying and deleting tables.
5. Views.
HNEU, Department of Information Systems, Course Database, V. V. Fedko 2
En: Test questions Ru:
1. Features and writing SQL commands. 1. Особенности и запись команд SQL
2. Write down the instructions for creating 2. Запишите оператор создания таблицы
the table Manufacturers (ManufacturerId, Производители (Код_проиводителя,
Name, Address, Telephone). Название, Адрес, Телефон)
3. Set the relationship between the 3. Установите связь между таблицами
Manufacturers and Sales tables by the Производители и Продажи по значениям
values of the ManufacturerId fields. полей Код_производителя.
Send your answers at email
[email protected] HNEU, Department of Information Systems, Course Database, V. V. Fedko 3
1. Language communication with DBMS
Characteristics of linguistic means of communication with the DBMS :
Database language is a general term referring to the class of languages used to
define and access databases.
Database language consists of two parts (sublanguages):
Data Definition Language (DDL)
Data Manipulation Language (DML)
These languages are called data sublanguages because they do not include
constructs for all computational needs, such as conditional or iterative
operators, which are provided by high-level programming languages.
HNEU, Department of Information Systems, Course Database, V. V. Fedko 4
Features and writing SQL commands
An SQL statement consists of:
• reserved words - a fixed part of the SQL language and have a fixed meaning. They must be
spelled exactly as required and cannot be split across lines.
• user-defined words - made up by the user (according to certain syntax rules) and represent
the names of various database objects such as tables, columns, views, indexes, and so on.
Most components of an SQL statement are case-insensitive
Exception: literal character data: ‘SMITH’ <> ‘Smith’
For more readability:
• each clause in a statement should begin on a new line;
• the beginning of each clause should line up with the beginning of other clauses;
• if a clause has several parts, they should each appear on a separate line and be indented
under the start of the clause to show the relationship.
HNEU, Department of Information Systems, Course Database, V. V. Fedko 5
Example
SELECT Sale_date, Name, Quantity
FROM Sales JOIN Products
ON Sales.ProductId = Products.ProductId
WHERE ProductId = 1 AND Sale_date='01.01.2018';
HNEU, Department of Information Systems, Course Database, V. V. Fedko 6
2. SQL DDL Language
Features of SQL Data Definition Language Commands:
A data definition language is the creation, modification, and destruction of a database
and the objects inside it (tables, views, etc.).
Objects :
Operations: DATABASE
CREATE TABLE
ALTER VIEW
DROP INDEX
SCHEMA
DOMAIN
HNEU, Department of Information Systems, Course Database, V. V. Fedko 7
Database creation
CREATE DATABASE DB_Name [Parameters];
• The list and possible values of the parameters
depend on the specific DBMS and most often
describe USE master;
• physical parameters of the database, GO
• security controls, CREATE DATABASE Bread;
• language parameters, GO
• etc.
• It is recommended to create a database and DROP DATABASE Bread
configure its parameters using special utilities
available in a specific industrial database.
HNEU, Department of Information Systems, Course Database, V. V. Fedko 8
Example: MS SQL Server 2014
USE master;
GO
CREATE DATABASE Sales
ON
( NAME = Sales_dat,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\saledat.mdf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = Sales_log,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\salelog.ldf',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB ) ;
GO
HNEU, Department of Information Systems, Course Database, V. V. Fedko 9
3. DDL commands for create tables
Before creating a table :
you need to know the following parameters: • Memory size to store each column
• Table name • The columns that define the primary key
• Column names • Columns whose values need to be entered
• Data type of each column • Default Values for Columns
PRODUCTS Table name
PRODUCT_ID NAME PRICE PURCHASE_PRICE
Primary key 1 Bread "Ukrainian" 13.50 12.00
Column
2 Long loaf "Milk" 12.80 12.50
names
3 Bun with poppy seeds 10 9
int Not Null nvarchar(25) Not Null Decimal(5, 2)
HNEU, Department of Information Systems, Course Database, V. V. Fedko 10
The syntax of the table creation operator (not full)
CREATE TABLE table_name
{(column_name data_type [NOT NULL][UNIQUE]
[DEFAULT <value>]
[ CHECK (<logical_expression>)][,...n]}
[CONSTRAINT constraint_name]
[PRIMARY KEY (column_name[,...n])
{[UNIQUE (column_name[,...n])}
[FOREIGN KEY (column_name_of_foreign_key[,...n])
REFERENCES parent_table_name
[(column_name_of_parent_table[,...n])],
[MATCH {PARTIAL | FULL}]
[ON UPDATE {CASCADE| SET NULL |SET DEFAULT |NO ACTION}]
[ON DELETE {CASCADE| SET NULL |SET DEFAULT |NO ACTION}]
{[CHECK(<logical_expression>)][,...n]})
HNEU, Department of Information Systems, Course Database, V. V. Fedko 11
Data types: INT DATE
CHAR(n) SMALLINT TIME
NCHAR(n) BIGINT TIMESTAMP
NVARCHAR(n) REAL INTERVAL
DOUBLE PRECISION BIT [VARYING] [n]
FLOAT(n)
DEC(i, j), NUMERIC(i, j)
Domain Constraints PRICE Decimal(5, 2) CHECK(PRICE > 1 AND PRICE <=50) DEFAULT(10)
CHECK (Condition)
HNEU, Department of Information Systems, Course Database, V. V. Fedko 12
The basic syntax of the table creation operator
CREATE TABLE table_name
(column_name data_type [PRIMARY KEY] [NULL | NOT NULL] [, ... n])
CREATE TABLE Products(
ProductId int IDENTITY(1,1) PRIMARY KEY,
Name nvarchar(25) NOT NULL,
Price money NULL,
Purchase_price money NULL
)
HNEU, Department of Information Systems, Course Database, V. V. Fedko 13
Referential Integrity
Foreign key is a column, or set of columns, that links each row in the child table
containing the foreign key to the row of the parent table containing the matching
candidate key value.
Referential integrity means that, if the foreign key contains a value, that value must refer
to an existing, valid row in the parent table
In child table
FOREIGN KEY (column_in_ child_table [,...n])
REFERENCES parent_table_name [(column_in_ parent_table [,...n])]
[ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
[ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
HNEU, Department of Information Systems, Course Database, V. V. Fedko 14
PRODUCTS Parent
PRODUCT_ID NAME PRICE PURCHASE_PRICE
1 Bread "Ukrainian" 13.50 12.00
2 Long loaf "Milk" 12.80 12.50
3 Bun with poppy seeds 10 9
1 Child
N SALES
SALE_ID SALE_DATE PRODUCT_ID MANUFACTURER_ID QUANTITY
1 01.09.2019 1 1 200
Relationship
2 01.09.2019 2 1 250
3 01.09.2019 3 1 180
4 01.09.2019 1 2 220
5 02.09.2019 1 1 200
6 02.09.2019 2 2 180
Foreign key
HNEU, Department of Information Systems, Course Database, V. V. Fedko 15
Child table
CREATE TABLE Sales(
SaleId int IDENTITY(1,1) PRIMARY KEY,
Sale_date date NULL,
ProductId int NOT NULL REFERENCES Products(ProductId)
ON DELETE CASCADE,
ManufacturerId int,
Quantity smallint NOT NULL
CHECK (Quantity>0 AND Quantity>500),
CONSTRAINT U1_Sales
UNIQUE(ProductId, ManufacturerId, Sale_date)
)
HNEU, Department of Information Systems, Course Database, V. V. Fedko 16
Diagram
HNEU, Department of Information Systems, Course Database, V. V. Fedko 17
4. Modifying and deleting tables
ALTER TABLE:
• add a new column to the table;
• delete column from table;
• add a new restriction to the table definition;
• remove the existing limit from the table definition;
• set the default value for the column;
• cancel the default value for the column.
HNEU, Department of Information Systems, Course Database, V. V. Fedko 18
Modifying table
ALTER TABLE table_name
{[ALTER COLUMN column_name {new_data_type [ NULL | NOT NULL ]}] |
ADD { [column_name data_type] | [column_name AS expression} [,...n] |
DROP {COLUMN column_name}[,...n]
ALTER TABLE Products
ADD Sort int;
ALTER TABLE Products
ADD CONSTRAINT CN_Sort CHECK (Sort >=0 AND Sort =<3);
ALTER TABLE Sales
DROP CONSTRAINT U1_Sales;
HNEU, Department of Information Systems, Course Database, V. V. Fedko 19
Deleting table
DROP TABLE table_name
DROP TABLE Products;
HNEU, Department of Information Systems, Course Database, V. V. Fedko 20
6. Views
Definition, use and features:
View is a temporary derivative (otherwise virtual) table and is a database object,
information in which is not stored permanently, as in the base table, but is formed
dynamically when it is called (stored query).
Using views allows the database developer to provide each user or group of users with
the most appropriate ways to work with the data, which solves the problem of ease of
use and security.
• A view cannot exist by itself, but is defined only in terms of one or more tables.
• View content is selected from other tables by executing a query, and when the values
in the tables change, the data in the view automatically changes.
HNEU, Department of Information Systems, Course Database, V. V. Fedko 21
Creating View
CREATE VIEW view_name [ (column [ ,...n ] ) ] CREATE VIEW PriceList
AS select_statement AS
SELECT Name, Price, Price* 0.2 AS Tax
Using View FROM Products
WHERE Price > 10;
You can use the view to select data just like a GO
table. Select * FROM PriceList;
Deleting View
DROP VIEW PriceList;
HNEU, Department of Information Systems, Course Database, V. V. Fedko 22
Updatable Views
You can modify the data of an underlying base table through a view, as long as the
following conditions are true:
• Any modifications, including UPDATE, INSERT, and DELETE statements, must
reference columns from only one base table.
• The columns being modified in the view must directly reference the underlying
data in the table columns. The columns cannot be derived in any other way, such
as through the following:
• An aggregate function: AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV,
STDEVP, VAR, and VARP.
• A computation. The column cannot be computed from an expression that
uses other columns.
• The columns being modified are not affected by GROUP BY, HAVING, or DISTINCT
clauses.
HNEU, Department of Information Systems, Course Database, V. V. Fedko 23
En: Test questions Ru:
1. Features and writing SQL commands. 1. Особенности и запись команд SQL
2. Write down the instructions for creating 2. Запишите оператор создания таблицы
the table Manufacturers (ManufacturerId, Производители (Код_проиводителя,
Name, Address, Telephone). Название, Адрес, Телефон)
3. Set the relationship between the 3. Установите связь между таблицами
Manufacturers and Sales tables by the Производители и Продажи по значениям
values of the ManufacturerId fields. полей Код_производителя.
Send your answers at email
[email protected] HNEU, Department of Information Systems, Course Database, V. V. Fedko 24