DATABASE ORGANIZATION
Lecturer: Ph.D. , Associate Professor, Associate Professor of Department 105
National Aerospace University
"Kharkiv Aviation Institute"
Karatanov Oleksandr Volodymyrovych
What will you learn in this course?
Conceptual database model
Database data model
Physical model of the database
SQL
Database design
DDL
DML
DQL
View
What will you learn in this course?
Development of a database for the client
in Visual Studio . C#.
User interface
Database connection
Database navigation and search
Delegates
Who can you become after studying the course?
Most popular languages
Programming, scripting, and markup languages
Most popular languages
© Zecomms Agency , 2023
Most popular languages (Djinni)
Database administrator salaries abroad
https://money.usnews.com/careers/best-jobs/database-administrator/salary
Database Engineer – FinTech
Database
Data models
Data models
Data models
Infological
Datalogical
Documentary
Factual
Graph-theoretic
Network
Hierarchical
Set-theoretic
Relational
Object-oriented
Physical
Types of data models
Hierarchical
Network
Relational
Hierarchical data model
Root
Descendant
Ancestor
Bypass procedure
Network data model
In a network model, connections between all information objects and all others are possible.
For example, each teacher can teach many students and each student can study with many teachers.
Using hierarchical or network models speeds up access to information, but requires significant memory resources .
Teacher 1
Teacher 2
Teacher 3
Student 1
Student 2
Student 3
Student 4
Semantic network
Relational data model
Subject area model
When designing a database, the subject area is in the form of three models:
The data logical model is designed based on the information model, by normalizing it and reducing it to third normal form.
Database design
0. Analysis of the subject area.
database design process is a sequential transition from an informal verbal description of the information structure of a subject area to a formalized description in terms of a certain model and, in turn, includes several stages.
DEVELOPMENT OF AN INFOLOGICAL MODEL
0 Domain Analysis
As a result, we should get a verbal description of the information objects of the subject area.
Designing an information model
Development of a data logical model
Physical database design
Subject area
Example of a subject area description
1 Designing an infological model
Designing an information model
Development of a data logical model
Physical database design
Designing an infological model
Entity- relationship model ( ER model ) ERM) – a data model that allows you to describe the conceptual schemes of a subject area.
IDEF1X (IDEF1 Extended ) Data Modeling – database modeling methodology based on the entity-relationship model.
It is used to build an information model that represents the structure of information necessary to support the functions of a production system or environment.
Basic concepts of ER diagrams
Essence
Entity instance
No. | Full name | Specialty | Group |
1 | Bozhenko Liliya Serhiivna | 123 Computer Engineering | 535-in |
Entity attribute
Entity key
Simple and compound key
Compound key
Simple key
Natural vs Surrogate Key
Communication
"A teacher can have multiple Disciplines",
"Every student must study at least one specialty."
Types of relationships between entities
Overview of software for designing database architecture
Crow's Foot Notation� (Crow's foot)
Types of connections in �Crow's Foot notation
Description | Symbol |
Circle and dash: minimum 0, maximum 1 (optional) | |
Two dashes: minimum 1, maximum 1 (required) | |
Circle and crow's foot: minimum 0, maximum many (optional) | |
Dash and crosier: minimum 1, maximum many (required) | |
The inner element of the notation represents the minimum value, and the outer element (closest to the essence) represents the maximum.
Subject area
ID | Full name | Faculty | Chair | Group | Rating for "OD" | OBD assessment |
1 | Duraev Andriy Sergeevich | 1 | 105 | 126 | failure to complete | unsatisfactorily |
2 | Barely Stanislav Yuriyovych | 1 | 105 | 126 | test | perfectly |
3 | Shifershtein Eduard Volodymyrovych | 1 | 105 | 126 | test | satisfactorily |
Data model
DEVELOPMENT OF A DATA LOGICAL MODEL
Normalization of relations
Normalization is a sequential process of partitioning and transforming some small source set of tables to construct a set of interdependent tables in normal forms.
Definition for the alternatively gifted
Normalization – this is when we had a lot of tables, and we would make even more so that they would comply with some rules.
Designing an information model
Development of a data logical model
Physical database design
Normal form
Normal form (NF) is a requirement for the structure of tables in theory relational databases to remove redundant data from the database functional dependencies between attributes (table fields).
eight NFs in total :
– 1-6 NF;
– NF Boyce-Codd;
– domain-key NF.
Functional dependency
A set of attributes Y is functionally dependent on X if and only if at any point in time for each of the different values of Y there is only one of the different values of X.
There is also an equivalent term: plural X determines Y .
Designation –
X → Y .
Each of the normalization levels restricts the types of allowable functional dependencies of a relation.
determinant
dependent part
Functional dependency. Example
schedule (Pilot, Flight, Date, Time).
1 normal form
Atomicity ( indivisibility ) of a field means that the values it contains must not be divided into smaller ones.
1 normal form. Example
Flight | ||
Number | Destination | Departure |
1 | Kharkiv | Mon , 9:40 |
1 | Kharkiv | Wed, 10:20 |
632 | Kyiv | Mon , 6:00 |
632 | Kyiv | Tue , 6:00 |
Duplication of information
Lack of atomicity
1 normal form. Example
Flight (Number, Destination, Departure day, Departure time).
Flight | ||
No. | Destination | Departure |
1 | Kharkiv | Mon , 9:40 |
1 | Kharkiv | Wed, 10:20 |
632 | Kyiv | Mon , 6:00 |
632 | Kyiv | Tue , 6:00 |
Allocating destinations to a separate table will eliminate duplication of information.
Flight | |||
No. | Destination | Departure day | Departure time |
1 | Kharkiv | Mon | 9:40 |
1 | Kharkiv | Wed | 10:20 |
632 | Kyiv | Mon | 6:00 |
632 | Kyiv | Tue | 6:00 |
Flight | |||
No. | Destination ID | Departure day | Departure time |
1 | 78 | Mon | 9:40 |
1 | 78 | Wed | 10:20 |
632 | 193 | Mon | 6:00 |
632 | 193 | Tue | 6:00 |
Destination | |
Destination ID | Destination |
78 | Kharkiv |
193 | Kyiv |
1 normal form. Example 2
Teachers | ||
No. | Full name | Unit |
1 | Karatanov O. V. | 1, 105 |
2 | Krytskyi D. M. | 1, 105 |
3 | Brega D. A. | 1, 101 |
Teachers | |||
No. | Full name | Faculty | Chair |
1 | Karatanov O. V. | 1 | 105 |
2 | Krytskyi D. M. | 1 | 105 |
3 | Brega D. A. | 1 | 101 |
1 normal form. Redundancy
Employee number | Name | Specialty | Manager number | Building No. |
1235 | Kameneva | Electrician | 1311 | 312 |
1235 | Kameneva | Electrician | 1311 | 515 |
1412 | Wet | Plasterer |
| 312 |
1412 | Wet | Plasterer |
| 460 |
1412 | Wet | Plasterer |
| 435 |
1412 | Wet | Plasterer |
| 515 |
1311 | Dosya | Electrician |
| 435 |
Employee | Name | Specialty | Manager number | No. buildings |
1235 | Kameneva | Electrician | 1311 | {312, 515} |
1412 | Wet | Plasterer |
| {312, 460, 435, 515} |
1311 | Dosya | Electrician |
| 435 |
Data redundancy – data duplication in the database.
Reduction to first normal form provokes redundancy
Example 3
1 normal form. Integrity
Data integrity – consistency of data in the database.
Anomalies
Update anomaly
Removal anomaly
Input anomaly
1st normal form. Example 4
Employee's record number | Name | Department number | Department | Project number | Project name | Task number |
1 | Karpenko | 1 | 11-22-33 | 1 | Space | 1 |
1 | Karpenko | 1 | 11-22-33 | 2 | Climate | 1 |
2 | Yen | 1 | 11-22-33 | 1 | Space | 2 |
3 | Konovalova | 2 | 33-22-11 | 1 | Space | 3 |
3 | Konovalova | 2 | 33-22-11 | 2 | Climate | 2 |
EMPLOYEES_DEPARTMENTS_PROJECTS
1st normal form. Example 4
Employee's record number | Name | Department number | Department |
1 | Karpenko | 1 | 11-22-33 |
2 | Yen | 1 | 11-22-33 |
3 | Konovalova | 2 | 33-22-11 |
Table 2. Relationship EMPLOYEES_DEPARTMENTS
Project number | Project name |
1 | Space |
2 | Climate |
Table 3. Relationship PROJECTS
Functional dependencies:
Project number
→ Project name
Employee's record number | Project number | Task number |
1 | 1 | 1 |
1 | 2 | 1 |
2 | 1 | 2 |
3 | 1 | 3 |
3 | 2 | 2 |
Table 4. TASKS relationships
Functional dependencies:
( Employee's record number , Project number ) → Task number
Functional dependencies:
Dependence of attributes characterizing an employee on the employee's personnel number:
Registration number → Last name
Registration number → Department number
Dependence of phone number on department number:
Department number → Department phone number
2 normal form
A simple key is a key with a single attribute.
A composite key is a key made up of two or more attributes.
Complete and partial functional dependence
2nd normal form. Example
Employee's record number | Name | Department number | Department |
1 | Karpenko | 1 | 11-22-33 |
2 | Yen | 1 | 11-22-33 |
3 | Konovalova | 2 | 33-22-11 |
Table 2. Relationships DEPARTMENT EMPLOYEES
Department number | Department |
1 | 11-22-33 |
2 | 33-22-11 |
Employee's record number | Name | Department number |
1 | Karpenko | 1 |
2 | Yen | 1 |
3 | Konovalova | 2 |
3 normal form
A non-key attribute is an attribute that is not part of the primary key.
Two or more attributes are called mutually independent if none of them is functionally dependent on any combination of the other attributes.
3rd normal form. �Alternative definition
A transitive functional dependency is a dependency where two attributes are related to each other through a third attribute.
+ and – normalizations
Criterion | The relations are weakly normalized (1NF, 2NF) | The relationship is strongly normalized (3NF) |
Adequacy of the subject area database | WORSE (-) | BETTER (+) |
Ease of database development and maintenance | MORE DIFFICULT (-) | EASIER (+) |
Insert, update, delete execution speed | SLOWER (-) | FASTER (+) |
Data sampling speed | FASTER (+) | SLOWER (-) |
HIGHER NORMAL FORMS
BCNF ( Boyce -Codd Normal Form)
Boyce-Codd normal form conditions :
�
Alternative item 2
Potential key
Potential key – in the relational data model – a subset of the attributes of a relationship that satisfies the requirements of uniqueness and minimality (irreducibility/ atomicity ).
Uniqueness means that there are no two tuples of this relation in which the values of this subset of attributes are the same (equal).
BCNF ( Boyce -Codd Normal Form)
N court | Start time | End time | Tariff |
1 | 09:30 | 10:30 | "Frugal" |
1 | 11:00 | 12:00 | "Frugal" |
1 | 14:00 | 15:30 | "Standard" |
2 | 10:00 | 11:30 | "Premium- B" |
2 | 11:30 | 13:30 | "Premium- B" |
2 | 15:00 | 16:30 | "Premium-A" |
Tariff | N court | Clubman |
"Frugal" | 1 | Yes |
"Standard" | 1 | No |
"Premium-A" | 2 | Yes |
"Premium- B" | 2 | No |
Tariff | Start time | End time |
"Frugal" | 09:30 | 10:30 |
"Frugal" | 11:00 | 12:00 |
"Standard" | 14:00 | 15:30 |
"Premium- B" | 10:00 | 11:30 |
"Premium- B" | 11:30 | 13:00 |
"Premium-A" | 15:00 | 16:30 |
�
The disadvantage of this structure is that, for example, the "Economical" rate can be mistakenly attributed to a reservation of 2 courts, although it may only apply to 1 court.
Fourth Normal Form (4 NF)
Conditions of the fourth normal form :
Alternative item 2
Fourth normal form
Relations with non-trivial multivalued dependencies typically arise from the natural combination of two relations on a common field that is not a key in either relation. This effectively results in an attempt to store information about two independent entities in a single relation.
For example, an employee may have many jobs and many children. Storing information about jobs and children in a single relation results in a non-trivial multivalued dependency Employee - Job - Children.
Fourth normal form
Entrant | Faculty | Subject |
Fedorenko | Aircraft construction | Mathematics |
Fedorenko | Aircraft construction | Informatics |
Fedorenko | Sula | Mathematics |
Fedorenko | Sula | Physics |
Shelepova | Aircraft construction | Mathematics |
Shelepova | Aircraft construction | Informatics |
Entrant | Faculty |
Fedorenko | Aircraft construction |
Fedorenko | Sula |
Shelepova | Aircraft construction |
Faculty | Subject |
Aircraft construction | Mathematics |
Aircraft construction | Informatics |
Sula | Mathematics |
Sula | Physics |
"Applicants-Faculties-Subjects" has a non-trivial multivalued dependency:
Faculty→→ Applicant | Subject.
Fourth Normal Form (4 NF)
There seems to be an update anomaly related to the fact that the names of applicants, names of faculties, and names of subjects are duplicated.
Elimination: by moving all names into separate relations, leaving only the corresponding numbers in the original relation.
Insertion anomaly . When trying to add a new tuple to the relationship "Applicants-Faculties-Subjects", for example ( Star , Aircraft Construction, Mathematics), we must also add a tuple ( Star , Aircraft Engineering, Computer Science), since all applicants to the Aircraft Engineering Faculty are required have the same list of items to be given. Accordingly, when trying to insert the tuple (3, 1, 1) into the modified relation, we must also insert the tuple (3, 1, 2).
Entrant | Faculty | Subject |
Fedorenko | Aircraft construction | Mathematics |
Fedorenko | Aircraft construction | Informatics |
Fedorenko | Sula | Mathematics |
Fedorenko | Sula | Physics |
Shelepova | Aircraft construction | Mathematics |
Shelepova | Aircraft construction | Informatics |
Item No. | Subject |
1 | Mathematics |
2 | Informatics |
3 | Physics |
Applicant number | Faculty No. | Item No. |
1 | 1 | 1 |
1 | 1 | 2 |
1 | 3 | 1 |
1 | 3 | 3 |
2 | 1 | 1 |
2 | 1 | 2 |
Applicant number | Entrant |
1 | Fedorenko |
2 | Shelepova |
Faculty No. | Faculty |
1 | Aircraft construction |
2 | Aviation engines |
3 | Sula |
4 | RCT |
5 | RTS LA |
6 | Economic |
7 | Humanitarian |
Applicant number | Faculty No. |
1 | 1 |
2 | 1 |
Faculty No. | Item No. |
1 | 1 |
1 | 2 |
3 | 1 |
3 | 3 |
Removal anomaly.
Insertion and deletion of tuples cannot be performed independently of other tuples of the relation.
In addition, if we delete these tuples, information about the subjects that must be taken at the SULA faculty will be lost.
Fifth Normal Form (5NF)
Conditions of the fifth normal form ( projective -adjoint normal form) :
Alternative item 2
Fifth Normal Form (5 NF)
Suppose that it is necessary to take into account the following restriction : each seller has in his assortment a limited list of firms and a limited list of types of good goods and offers goods from the list of goods, produced by firms from the list of firms.
In the example, in particular, it is assumed that the seller Bova has the right to sell goods only from the company "Rogy ta Kopyta", the seller Oliynyk - goods only from the company "Kalashnikov", however, the seller Karpenko does not have the right to sell barbiturates and steroids, etc.
Seller | Firm | Goods |
Bova | Horns and hooves | Amphetamine |
Bova | Horns and hooves | Barbiturates |
Oil varnish | Kalashnikov | AK-74 |
Oil varnish | Kalashnikov | Steroids |
Karpenko | Horns and hooves | Amphetamine |
Karpenko | Horns and hooves | Heroin |
Karpenko | Kalashnikov | AKS-74U |
Seller | Goods |
Bova | Amphetamine |
Bova | Barbiturates |
Oil varnish | AK-74 |
Oil varnish | Steroids |
Karpenko | Amphetamine |
Karpenko | Heroin |
Karpenko | AKS-74U |
Sellers' goods
Seller | Firm |
Bova | Horns and hooves |
Oil varnish | Kalashnikov |
Karpenko | Horns and hooves |
Karpenko | Kalashnikov |
Firm | Goods |
Horns and hooves | Amphetamine |
Horns and hooves | Barbiturates |
Kalashnikov | AK-74 |
Kalashnikov | Steroids |
Horns and hooves | Heroin |
Kalashnikov | AKS-74U |
Companies sellers
Goods firms
Non-trivial connection dependency
Sixth normal form
Time | Position |
2020 | schoolboy |
2023 | student |
Time | Position | Marital status |
2020 | schoolboy | In active search |
2022 | schoolboy | I meet you. |
2023 | schoolboy | In love |
2023 | student | In love |
2024 | student | Everything is complicated. |
2025 | student | Unmarried |
Time | Marital status |
2020 | In active search |
2022 | I meet you. |
2023 | In love |
2024 | Everything is complicated. |
2025 | Unmarried |
Domain- key normal form
Alternative definition: a relation is in DCNF if it has no modification anomalies.
This is achieved by adding additional constraints on the values of the record field. Data integrity maintenance relies on the mechanisms of a specific DBMS . For example, default field values, data range restrictions, triggers that fire when creating, modifying, or deleting records, and so on. In short, anything that helps maintain data integrity. It was proposed by Ronald Fagin in 1981.
Domain -key normal form (DKNF) is a form where any operation of adding or deleting a record cannot lead to a violation of data integrity.
Domain restrictions – a constraint that requires that only values from a specific domain be used for a particular attribute. A constraint is essentially a list (or logical equivalent of a list) of permissible values of a type and a declaration that the specified attribute has that type.
Key constraint – a constraint that states that a particular attribute or combination of attributes is a potential key.
DEVELOPMENT OF �A PHYSICAL MODEL
DBMS
Data Management System ( DBMS ) (DBMS ) – a set of language and software tools that provide database management [GOST 34.321-96].
Alternative definition
A DBMS is a program, or a set of programs, designed for full-featured work with data.
Typically, it includes tools for creating and modifying the storage structure of data sets, as well as means of accessing stored data with the ability to read, add, modify, and delete it.
The DBMS is designed to play the role of an intermediary between the user (or rather, his direct query or the application in which the query is formulated) and the database.
Information model design
Development of data logic model
Physical database design
Classification of DBMS. �By method of accessing the database
Database classification. �By data model
Classification of DBMS. �By level of distribution
File server
|
|
|
|
| Microsoft Access |
| Paradox |
| dBase |
| FoxPro |
Client-server
|
|
|
|
| Oracle |
| MySQL |
| MS SQL Server |
| PostgreSQL |
File server vs. Client -server
- user interface,
- processing logic ,
- data management
- user interface,
- processing logic
- data storage
- data storage
- processing logic ,
- data management
File server
Client-server
Server
Clients
High network load – large amounts of data are being transferred
Low network load – requests and results are transmitted
Built-in
|
|
|
|
| SQLite |
| Firebird Embedded |
| Built-in H2 |
| Built-in version Interbase |
Database rating
All users Beginners
Database rating
https://db-engines.com/en/ranking_trend
MySQL Workbench
How to install MySQL Workbench on Windows?
MySQL Workbench – a tool for visual database design.
MySQL Workbench is NOT a DBMS!
MySQL Workbench
MySQL Workbench
MySQL Workbench . �Visual design
MySQL Workbench
MySQL Workbench
MySQL Workbench. �Creating a new data model
.
To create a new table on the Physical schema tab ( Physical Schemas ) select " Add Table » and fill in the fields
MySQL Workbench
Next, go to the " Columns " tab and create table fields.
Enter the field name, data type, parameters, and comment for it.
Each column has:
1 name (do not use Cyrillic characters in the name!),
Data type 2. The most common data types:
3 PK ( primary key ) – primary key;
4 NN ( not null ) – the cell does not allow empty values;
5 U Q ( unique ) – the value must be unique within the column;
6 AI ( auto incremental) – this property is useful for a simple primary key, it means that the primary key will be automatically filled with natural numbers 1, 2, 3, etc.;
7 DEFAULT – default value, that is, the value that is automatically inserted into the cell by the server when adding a new row to the table if the user left the cell blank.
Data types
| BOOL or BOOLEAN |
Size | 1 bytes |
Minimum value | 0 |
Maximum value | 1 |
Numeric integer types
| TINYINT | SMALLINT | MEDIUMINT | INT | BIGINT |
Size | 1 byte | 2 bytes | 3 bytes | 4 bytes | 8 byte |
Minimum value | -128 | -32768 | -8388608 | -2 32 = -2147483648 | -2 63 = -9223372036854775808 |
Maximum value | 127 | 32767 | 8388607 | 2 32 -1 = 2147483647 | 2 63 - 1 = 9223372036854775807 |
Minimum unsigned value | 0 | 0 | 0 | 0 | 0 |
Maximum unsigned value | 255 | 65535 | 16777215 | 4294967295 | 18446744073709551615 |
Numerical thing types
| FLOAT (M, D) | DOUBLE (M,D ) | DECIMAL (M,D) or DEC (M, D) or NUMERIC (M, D) |
Size | 4 bytes | 8 bytes | M + 2 bytes |
Minimum value | -1.175494351 × 10 -39 | -2.2250738585072015 × 10 -308 | depend on the parameters M and D |
Maximum value | 3. 402823466 × 10 38 | 1.797693134862315 × 10 308 |
Character data types
| character | varchar | nchar | nvarchar |
Coding | Non- Unicode | Non- Unicode | Unicode | Unicode |
Maximum length | 8000 | 8000 | 4000 | 4000 |
Character size | 1 byte | 1 byte | 2 bytes | 2 bytes |
Storage size | n bytes | n + 2 bytes | 2 × n bytes | 2 × n + 2 bytes |
Using | If the length of the string is strictly fixed | For variable length strings | Use only if you need support for Unicode characters, such as Japanese ( Kanji ) or Korean ( Hangul ) characters. | |
Calendar data types
| DATE | TIME | DATATIME | TIMESTAMP | YEAR ( 2 ) | YEAR ( 4 ) |
Sense | Date | Time of day | Date and time of day | Date and time of day as seconds since midnight on January 1, 1970 (the beginning of the UNIX era) | Year (two-digit) | Year |
Size | 3 bytes | 3 bytes | 8 bytes | 4 bytes | 1 byte | 1 byte |
Format | YYYY-MM-DD | hh:mm:ss | YYYY-MM-DD hh:mm:ss | YYYY-MM-DD hh:mm:ss | YY | YYYY |
Minimum value | 1000-01-01 | -838:59:59 | 1000-01-01 00:00:00 | 1970-01-01 00:00:00 | 1970 | 1901 |
Maximum value | 9999-12-31 | 838:59:59 | 9999-12-31 23:59:59 | 2037-12-31 23:59:59 | 2069 | 2155 |
Calendar data types
Other types
| BLOB, TEXT | MEDIUMBLOB, MEDIUMTEXT | LONGBLOB, LONGTEXT | ENUM ('value1', 'value2', ...,' valueN ') | SET ('value1', 'value2', ...,' valueN ') |
Size | L+2 characters | L+3 characters | L+4 characters | 1 or 2 bytes | up to 8 bytes |
Maximum value | 2 16 -1 characters | 2 24 -1 characters | 2 32 -1 characters | 65535 items | 64 items |
http://www.mysql.ru/docs/man/ENUM.html
MySQL
MySQL Workbench
After creating several tables, you can proceed to create relationships between them. You can do this either through the Foreign tab Keys in the required table, or directly when drawing a diagram of your database.
If you do it through the " Foreign" tab Keys ", then go to this tab, enter the name of your key and select the table for the relationship. Then, in the right part of the form, where the table with fields is indicated, select the fields of the previously specified table for the desired field, that is, this is where the relationship between the fields is indicated.
Here is the simplest example of a key:
ON DELETE
DDL
Integrity by reference
Integrity by reference
Integrity by reference
If such information exists, the update cannot be made.
MySQL Workbench
Creating a database diagram
To create a diagram, use the Model -> Add menu. Diagram ( Ctrl+T ) or on the " EER Diagrams " tab, click on the add new diagram button. A checkered drawing field will open. Select the required tables on the left in the table list and drag them with the mouse onto this checkered area. As a result, a complete diagram of these tables will be immediately built, taking into account the connections we created earlier .
That's all the drawing. Nothing complicated.
As you may have noticed here, there is a toolbar where you can choose to create a new table, images, comment blocks, blocks for merging tables, and various options for relationships between tables (one-to-one, one-to-many, etc. ). By the way, if you create a new table visually here, it will immediately be added to the model itself, i.e. you don't need to duplicate anything.
EER diagram ( EER = Enhanced Entity Relationship)
Creating an SQL CREATE script
MySQL database . To do this, you need to create an SQL script. Go to the menu. Select the menu item File -> Export -> Forward Engineer SQL CREATE Script .
In the window that appears in the Output field file using the Browse button Select the path to save the script and specify its name. Click the Next button .
In the next window, click the Finish button .
MySQL Workbench
Synchronization with the server
Select Database -> Synchronize Model… from the menu and enter your server parameters in the window.
After that, go further, the connection will be checked and, if everything is ok , you can proceed to selecting a model for synchronization. Here you select your model, and below you select the database on the server. Go further again, where all your data will be checked again.
After that, you will already be in the list of tables in your model in the program and in the database on the server. It is important that this synchronization method completely synchronizes data, i.e. not only does it upload new tables to the server, but it can also upload tables from the server to the program . To do this, just select the tables in the database and click the " Update Model " button so that they are uploaded to the model during synchronization.
Identifying and non-identifying relationships
There cannot be an order item number without an order.
Lecture 8. SQL language
SQL
SQL
Differences between SQL and relational theory
The SQL language uses terms that are somewhat different from relational theory terms, for example,
The SQL language standard, although based on relational theory, deviates from it in many places.
History of SQL
Most popular languages
Programming, scripting, and markup languages
Advantages of SQL
Bonus
Dialects SQL
How to use SQL?
127.0.0.1 (aka localhost ) is an IP address that a computer can use to contact itself over the network, regardless of whether it is connected to the network, the type, and the address of the computer on it.
How to use SQL?
How to study SQL ?
How to study SQL ?
CodePad.SQL
SELECT Product_ID, Name , Price
FROM product
WHERE price > 100
ORDER BY price Description
Useful links
Useful links
SQL language components
Operators SQL
DDL
CREATE
DROP
ALTER
DML
UPDATE
DELETE
INSERT
DQL
SELECT
DCL
GRANT
REVOKE
TCL
COMMIT
ROLLBACK
Operators SQL
DDL (Data Definition Language) – statements defining database objects
CREATE SCHEMA – create a database schema DROP SHEMA – delete a database schema
CREATE TABLE – create a table ALTER TABLE – alter a table DROP TABLE – delete a table
CREATE DOMAIN – create a domain ALTER DOMAIN – change a domain DROP DOMAIN – delete a domain
CREATE COLLATION – create a sequence DROP COLLATION – delete a sequence
CREATE VIEW – create a data view DROP VIEW – delete a data view
DML ( Data Manipulation Language ) – data manipulation operators
SELECT – select rows from tables
INSERT – add rows to a table
UPDATE – change rows in a table
DELETE – delete rows in a table
D C L ( Data Control Language ) – operators for working with access rights
CREATE ASSERTION – create a constraint DROP ASSERTION – remove constraint
GRANT – grant privileges to a user or program to manipulate objects
REVOKE – revoke user or program privileges
TCL ( Transaction Control Language ) – statements transaction management
COMMIT – commit changes
ROLLBACK – roll back changes made
DDL data definition statements
CREATE
DROP
ALTER
TABLE
VIEW
…
+
Name
tables /
kind
+
DDL data definition statements
Operator | Value | Action |
CREATE TABLE | Create a table | Creates a new table in the database |
DROP TABLE | Delete table | Deletes a table from the database. |
ALTER TABLE | Change table | Changes the structure of an existing table or the integrity constraints set for that table |
CREATE VIEW | Create a data slice | Creates a virtual table that corresponds to some SQL query |
DROP VIEW | Delete data slice | Deletes a previously created data slice |
ALTER VIEW | Change data slice | Changes a previously created data slice |
CREATE INDEX | Create index | Creating a table index for quick access to attributes included in the index |
DROP INDEX | Delete index | Deletes a previously created index |
Loading data using a text file
name | owner | species | sex | birth | death |
Fluffy | Harold | cat | f | 1993-02-04 |
|
Claws | Gwen | cat | m | 1994-03-17 |
|
Buffy | Harold | dog | f | 1989-05-13 |
|
Fang | Benny | dog | m | 1990-08-27 |
|
Bowser | Diane | dog | m | 1998-08-31 | 1995-07-29 |
Chirpy | Gwen | bird | f | 1998-09-11 |
|
Whistler | Gwen | bird |
| 1997-12-09 |
|
Slim | Benny | snake | m | 1996-04-29 |
|
name | owner | species | sex | birth | death |
Whistler | Gwen | bird | \N | 1997-12-09 | \N |
Let's say your records match the ones in this table (note: MySQL accepts dates in the format YYYY-MM-DD ; you may not be used to this notation).
Since you are starting with a blank table, the easiest way to fill it in is to create a text file containing a row for each animal, and then load its contents into the table with a single command.
Blank fields (such as unknown sex or death dates for animals alive today) can be given a NULL value. In a text file, this value is the characters \N.
For example, the entry for the bird Whistler should look something like this (single tabs should be placed between values):
The end-of-line marker and column-value separator can be specified in the LOAD DATA command, but the defaults are tab and newline. Assuming these, the command will be able to read the pet.txt file
You can load the pet.txt file into a table using the following command:
mysql > LOAD DATA LOCAL INFILE "pet.txt" INTO TABLEpet ;
CREATE TABLE pet ( name VARCHAR(20), owner VARCHAR(20), species VARCHAR(20), sex CHAR(1), birth DATE,death DATE);
SQL not SQL
CREATE DATABASE
CREATE DATABASE database_name [ ON
{[PRIMARY] (
NAME = logical_file_name,
FILENAME = 'os_file_name'
[, SIZE = size]
[, MAXSIZE = max_size]
[, FILEGROWTH = growth_increment] )
} [,...n]
]
[ LOG ON
{ ( NAME = logical_file_name,
FILENAME = 'os_file_name'
[, SIZE = size] )
} [,...n] ] [FOR RESTORE]
FILENAME – the full path and file name for the database location, must point to the local disk of the computer on which SQL Server is installed.
SIZE – initial size of each file in MB .
MAXSIZE – maximum file size in MB , if not specified, the size is not limited.
FILEGROWTH – the unit of volume added to a file each time it needs to be increased, specified in MB (by default) or as a percentage (i.e., 0 is added to the number); the value 0 prohibits the file from increasing.
1 MB – default
DCL
DROP DATABASE
DROP DATABASE databasename;
DCL
CREATE TABLE
CREATE TABLE table_name
(
column_name data_type [NULL | NOT NULL]
[,...n]
)
CREATE TABLE table (
column1 type1 [(size1)][CONSTRAINT _ column-constraint1]
[, column2 type2 [(size2)][CONSTRAINT _ column-constraint2]
[, ...]]
[CONSTRAINT table-constraint1 _ [,table-constraint2 [, ...]]]
);
DDL
CREATE TABLE
CREATE TABLE member (
member_no int NOT NULL ,
lastname char ( 50 ) NOT NULL ,
firstname char ( 50 ) NOT NULL ,
photo image
)
-- MySQL:
id INTEGER PRIMARY KEY AUTO_INCREMENT
-- MS SQL Server:
id INT identity ( 1 , 1 ) PRIMARY KEY
DDL
CREATE TABLE
CREATE TABLE Simple (
FirstName varchar ( 50 ) NOT NULL ,
LastName varchar ( 50 ) NOT NULL ,
Email varchar ( 50 ),
HomePage varchar ( 255 )
)
DDL
CREATE TABLE
CREATE TABLE Simple (
PersonID Integer NOT NULL PRIMARY KEY ,
FirstName varchar ( 50 ) NOT NULL ,
LastName varchar ( 50 ) NOT NULL ,
Email varchar ( 50 ),
HomePage varchar ( 255 )
)
DDL
CREATE TABLE Simple (
PersonID Integer NOT NULL PRIMARY KEY ,
FirstName varchar ( 50 ) NOT NULL ,
LastName varchar ( 50 ) NOT NULL ,
Email varchar ( 50 ),
HomePage varchar ( 255 ),
CONSTRAINT SimpleConstraint UNIQUE (FirstName, LastName)
)
DROP TABLE
DROP TABLE <table name>;
DDL
ALTER TABLE
DDL
ALTER TABLE
ALTER TABLE table name
�,
DROP column name
�ADD column name data type
(size) NOT NULL
NOT NULL WITH DEFAULT
,
RENAME column name new name
TABLE new name
,
MODIFY column name
data type ( length ) NULL
NOT NULL
NOT NULL WITH DEFAULT
Changes the structure of columns in a table.
ALTER TABLE �( Referential Integrity )
ALTER TABLE table name
,
PRIMARY KEY (column name)
DROP
,
,
FOREIGN KEY (column name) REFERENCES parent table name
DROP foreign key
name
ON DELETE RESTRICT
CASCADE
SET NULL
Changes the PRIMARY KEY/FOREIGN KEY structure in a table.
ALTER TABLE
ALTER TABLE table ADD [COLUMN] column datatype [(size)]
[CONSTRAINT sinlge-column-constraint]
ALTER TABLE Simple ADD Phone varchar ( 30 )
DDL
ALTER TABLE
DDL
ALTER TABLE
DDL
ALTER TABLE Departments
ADD PhoneDepartment VARCHAR ( 9 )
CHECK (PhoneDepartment LIKE '[2.5][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' )
ALTER TABLE Results ADD CONSTRAINT ch_res_marks
CHECK (Mark IN ( 3 , 4 , 5 )
AND ((Mark = 3 AND Balls BETWEEN 60 AND 75 )
OR ( Mark = 4 AND Balls BETWEEN 75 AND 90 )
OR (Mark = 5 AND Balls BETWEEN 90 AND 100 )));
ALTER TABLE
ALTER TABLE table ADD CONSTRAINT constraint
DDL
ALTER TABLE Departments
ADD CONSTRAINT un_title
UNIQUE (TitleDepartment);
ALTER TABLE
ALTER TABLE table DROP [COLUMN] column
DDL
ALTER TABLE Simple DROP Phone
ALTER TABLE
ALTER TABLE table DROP CONSTRAINT index
DDL
ALTER TABLE Simple DROP CONSTRAINT PrimaryKey
Data types in SQL
Data type | Description |
INTEGER, INT | Whole numbers |
SMALLINT | Small integers |
DECIMAL(p, q), DEC(p, q) (0 < p < 16 , q < p) | Decimal numbers |
FLOAT( n ) (n is the number of bytes) | Floating point substance |
REAL | Low precision floating point substance |
DOUBLE PRECISION | High precision floating point substance |
Data types in SQL
Data type | Description |
CHARACTER(n), CHAR( n ) (n – number of characters 0 < n < 254) | Constant-length character strings |
VARCHAR(n) | Variable-length character strings |
DATE | Date in a format that you specify special team (default ) mm / dd / yyy ) |
TIME | time in a format that you specify special team (default ) hh.mm.ss ) |
DATETIME | date and time combination |
MONEY | money |
Information entities of the " Rembrigada " database
Example of defining �tables for the Rembrigade database
CREATE TABLE WORKERS (
REGISTER_NUMBER INTEGER NOT NULL PRIMARY KEY ,
Full name CHARACTER ( 15 ),
SPECIALTY CHARACTER ( 15 ),
TIME_RATE DECIMAL ( 6 , 1 ),
BRIGADIER INTEGER
)
CREATE TABLE OBJECTS (
OBJECT_NUMBER INTEGER NOT NULL PRIMARY KEY ,
OBJECT_ADDRESS CHARACTER ( 15 ),
OBJECT_TYPE CHARACTER ( 9 ) DEFAULT 'office' CHECK (
TYPE IN ( 'office' , 'warehouse' , 'store' , 'residential building' )
),
DIFFICULTY_LEVEL INTEGER DEFAULT 1 CHECK (
DIFFICULTY LEVEL > 0
AND DIFFICULTY_LEVEL < 5
)
)
DDL
Example of defining �tables for the Rembrigada database
CREATE TABLE WORK (
REGISTER_NUMBER INTEGER NOT NULL ,
OBJECT_NUMBER INTEGER NOT NULL ,
START_DATE DATE ,
NUMBER_DAYS INTEGER ,
PRIMARY KEY ( TABLE_NUMBER, OBJECT_NUMBER),
FOREIGN KEY REFERENCES REFERENCES ON DELETE CASCADE WORKERS ,
FOREIGN KEY OBJECT_NUMBER REFERENCES ON DELETE CASCADE
)
DDL
Bonus operators for MySQL
SQL .DML
Data modification and sampling
DML
INSERT
DELETE
UPDATE
DQL
SELECT
Data manipulation operators�
Operator | Sense | Action |
DELETE | Delete rows | Deletes one or more rows that match the filter condition from the table. The result depends on the chosen strategy for maintaining referential integrity. |
INSERT | Insert line | Inserts a row into the table. are allowed in which several rows can be transferred from one table to the base table at once. |
UPDATE | Update row | Updates the values of one or more columns in one or more rows that meet the filter conditions. |
DML
INSERT statement
DML
INSERT [INTO] table ([column_list]
{ VALUES ( { DEFAULT | NULL | expression } } [, …] )
INSERT INTO Customers(CustomerID, CompanyName)
VALUES ( 'XYZFO' , 'XYZ Deli' )
DELETE operator
DML
DELETE FROM table [WHERE criteria]
DELETE FROM Product WHERE Discontinued = 1
When I execute a DELETE query and realize I forgot to add a WHERE
DML
UPDATE operator
DML
UPDATE table
SET column1 = expression1 [,
column2 = expression2][,…]
[WHERE criteria]
UPDATE Product
SET UnitPrice = UnitPrice * 1 . 1
WHERE Unit Price < 10
Test
CREATE TABLE STUDENTS (
ID INTEGER PRIMARY KEY,
FIRST_NAME VARCHAR (50) NOT NULL,
LAST_NAME VARCHAR (50) NOT NULL,
ADDRESS VARCHAR (100)
)
SQL .DQL
Data Query Language (DQL)
DQL
SELECT
DQL
SELECT column-list
FROM table-list
[ WHERE where-clause]
[ ORDER BY order-by-clause] ;
SELECT * FROM Table_name;
SELECT
DQL
SELECT
[DISTINCT | DISTINCTROW | ALL]
select_expression,...
FROM table_references
[ WHERE where_definition]
[ GROUP BY {unsigned_integer | col_name | formula}]
[ HAVING where_definition]
[ ORDER BY {unsigned_integer | col_name | formula} [ASC | DESC], ...] ;
FROM
DQL
SELECT * FROM Customers;
SELECT
DQL
SELECT CompanyName FROM Customers;
SELECT CompanyName, ContactName FROM Customers;
SELECT Customers.CompanyName, Shippers.CompanyName
FROM Customers, Shippers;
WHERE
DQL
WHERE expression1 [{AND | OR} expression2 […]]
SELECT * FROM Product WHERE CategoryID = 4 ;
WHERE
DQL
SELECT *
FROM Product
WHERE CategoryID = 2 AND SupplierID > 10 ;
�SELECT ProductName, UnitPrice
FROM Product
WHERE CategoryID = 3 OR UnitPrice < 50 ;
SELECT ProductName, UnitPrice
FROM Product
WHERE Discontinued IS NOT NULL ;
Comparison operators | |
< | Less |
<= | Less than or equal to |
<> | Not equal to |
= | Exactly |
> | More |
>= | Greater than or equal to |
Examples of simple queries
SELECT Full name
FROM ROB AND TNIKS
WHERE SPECIALTY = 'plasterer' ;
SELECT *
FROM OBJECTS
WHERE OBJECT_TYPE = 'office' ;
DQL
WHERE . �Special comparison operators
DQL
ALL
ANY
BETWEEN
IN
LIKE
WHERE. �Special comparison operators
DQL
SELECT CompanyName, ContactName
FROM Customers
WHERE CompanyName LIKE 'M%'
WHERE . �BETWEEN
DQL
SELECT CompanyName, ContactName
FROM Customers
WHERE CompanyName BETWEEN 'A' AND 'D'
WHERE. �Special comparison operators
DQL
SELECT CompanyName, ContactName FROM Customers
WHERE CompanyName LIKE '%bl%'
SELECT CompanyName, ContactName FROM Customers
WHERE CustomerID IN ( 'ALFKI' , 'BERGS' , 'VINET' )
Examples of simple queries
DQL
SELECT *
FROM WORKERS
WHERE Specialty IN ( 'plasterer' , 'roofer' )
Examples of simple queries
DQL
SELECT *
FROM Employees
WHERE Specialty LIKE ( 'elec%' )
WHERE + AND, OR, NOT
DQL
SELECT CompanyName, ContactName
FROM Customers
WHERE CompanyName LIKE 'S%' AND Country = 'USA'
SELECT CompanyName, ContactName
FROM Customers
WHERE Country NOT IN ( 'USA' , 'UK' )
Truth table of logical expressions
A | B | NOT A | A AND B | A OR B |
True | True | False | True | True |
True | False | False | False | True |
True | Null | False | Null | True |
False | True | True | False | True |
False | False | True | False | False |
False | Null | True | False | Null |
Null | True | Null | Null | True |
Null | False | Null | False | Null |
Null | Null | Null | Null | Null |
IS NULL
NULL 1 ≠ NULL 2
DQL
Examples of simple queries
DQL
SELECT *
FROM WORKERS
WHERE Hourly_rate >= 60
AND Hourly_rate <= 70
SELECT *
FROM WORKERS
WHERE Hourly_rate BETWEEN 60 AND 70
ORDER BY
DQL
ORDER BY column1 [{ASC | DESC}] [,
column2 [{ASC | DESC}] [,…]
ORDER BY
DQL
SELECT LastName, FirstName, Title
FROM Employees
ORDER BY LastName, FirstName
SELECT ProductName, UnitPrice
FROM Product
ORDER BY UnitPrice DESC
Examples of simple queries
SELECT Full name,
'Weekly salary = ' ,
40 * Hourly_rate
FROM WORKERS
WHERE SPECIALTY = 'electrician'
ORDER BY NAME
DQL
A short list of relational algebra operations
Operation | Marking | Application area |
Sample | | Defines a resulting relation that contains only those tuples (rows) from relation R that satisfy a given condition (predicate) |
Projection | | Defines a new relation containing a vertical subset of relation R, created by extracting the values of the specified attributes and excluding duplicate rows from the result. |
Association | | Defines a new relation that includes all tuples contained only in R, only in S, both in R and S, with all duplicate tuples excluded. The relations R and S must be union compatible. |
Difference | | The difference of two relations R and S consists of tuples that are present with respect to R but absent with respect to S. Moreover, the relations R and s must be compatible with respect to the union |
Crossing | | Defines a relation that contains tuples present in both R and S. The relations R and S must be union compatible. |
Cross connection | | Defines a new relation that results from concatenating (i.e., joining) each tuple from relation R with each tuple from relation S |
Theta connection | | Defines a relation that contains tuples from the Cartesian product of relations R and S that satisfy the predicate F |
Connection by equivalence | | Defines a relation that contains tuples from the Cartesian product of relations R and S that satisfy the predicate F (the predicate must only assume equality comparisons) |
Natural combination | | A natural join is a join by equivalence of two relations R and S, performed on all common attributes x, from the results of which one instance of each common attribute is excluded. |
(Left) outer join | | A join in which tuples of a relation R that do not have matching values in the common columns of a relation S are also included in the resulting relation |
Semi-union | | Defines a relation containing those tuples of the relation R that are included in the union of the relations R and S |
Divide | | Defines a relation consisting of a set of relation tuples R defined on an attribute C that corresponds to the combination of all tuples of a relation S, where C is the set of attributes present in R but absent in S. |
Sample
Name | Weight |
Volkov | 67 |
Dorohobid | 70 |
Vystoropskaya | 48 |
Persons
σ Weight ≥ 66 (Persons)
Name | Weight |
Volkov | 67 |
Dorohobid | 70 |
Projection
Name | Name | Patronymic |
Litvinov | Yaroslav | Oleksandrovich |
Lukashiv | Dmitry | Serhiyovych |
Ryabtsev | Nikita | Serhiyovych |
Persons
π Surname, First Name (Persons)
Name | Name |
Litvinov | Yaroslav |
Lukashiv | Dmitry |
Ryabtsev | Nikita |
Subtraction (difference)
Name |
Guobadia |
Yen |
Karpenko |
Name |
Guobadia |
Star |
Tkachenko |
Bank A clients ( R1 )
Bank B clients ( R2 )
Name |
Yen |
Karpenko |
R = R1 – R2
Customers of Bank A who are not customers of Bank B ( R )
Association
Name |
Guobadia |
Yen |
Karpenko |
Name |
Guobadia |
Star |
Tkachenko |
Bank A clients ( R1 )
Bank B clients ( R2 )
Name |
Guobadia |
Yen |
Karpenko |
Star |
Tkachenko |
R = R1 U R2
Customers ( R )
all duplicate tuples are excluded
Crossing
Name |
Guobadia |
Yen |
Karpenko |
Name |
Guobadia |
Star |
Tkachenko |
Bank A clients ( R1 )
Bank B clients ( R2 )
Name |
Guobadia |
R = R1 ∩ R2
Customers of two banks at the same time ( R )
Cross connection
Name |
Guobadia |
Yen |
Karpenko |
Name |
Guobadia |
Star |
Tkachenko |
Bank A clients ( R1 )
Bank B clients ( R2 )
Name | Name |
Guobadia | Guobadia |
Yen | Guobadia |
Karpenko | Guobadia |
Guobadia | Star |
Yen | Star |
R = R1 X R2
All variants of their combinations ( R )
Name | Name |
Karpenko | Star |
Guobadia | Tkachenko |
Yen | Tkachenko |
Karpenko | Tkachenko |
Divide
Name | Quality |
Bondarev | Humor |
Ryabtsev | Persistence |
Forelock | Self-criticism |
Quality |
Humor |
Alcoholism |
Sociability |
Persons( R1 )
Qualities ( R2 )
Name |
Bondarev |
R = R1 ÷ R2
From table R1, the values of the rows are taken for which all combinations of values from table R2(R) are present.
Table joins
DQL
SELECT ProductName, CategoryName FROM Product, Categories
SELECT ProductName, CategoryName
FROM Product, Categories
WHERE Product.CategoryID = Categories.CategoryID
INNER JOIN
DQL
SELECT ProductName, CategoryName
FROM Product
INNER JOIN Categories
ON Product.CategoryID = Categories.CategoryID
This is useful: in principle, there is no critical difference between using WHERE or JOIN to join tables, but it is believed that writing a query using JOIN is more correct due to readability.
LEFT JOIN
DQL
SELECT ProductName, CategoryName
FROM Product
LEFT OUTER JOIN Categories
ON Product.CategoryID = Categories.CategoryID
RIGHT JOIN
DQL
SELECT ProductName, CategoryName
FROM Product
RIGHT OUTER JOIN Categories
ON Product.CategoryID = Categories.CategoryID
FULL JOIN
DQL
SELECT ProductName, CategoryName
FROM Product
FULL OUTER JOIN
ON Product.CategoryID = Categories.CategoryID
Joins
CROSS JOIN
DQL
SELECT ProductName, CategoryName
FROM Product
CROSS JOIN Categories
SELECT ProductName, CategoryName
FROM Product,
Categories
Joining three tables
SELECT (fields) field_1 , field_2 , field_3
FROM (tables) table_1
JOIN (with table) table_2
Software (conditions) (foreign_key_field_of_table_1 = primary_key_field_of_table_2 )
JOIN (with table) table_3
Software (conditions) (foreign_key_field_of_table_2 = primary_key_field_of_table_3 );
Example of a query that joins 3 tables
SELECT hst_name, sit_name, vis_timestamp
FROM hosts
JOIN visits ON (hst_pcode = vis_hstcode)
JOIN websites ON (vis_sitcode = sit_pcode);
DQL
Natural joins �(NATURAL JOIN)
DQL
Similarly
The only one
a matching column
for tables emp and dept
there is a column
department no .
SELECT ename, deptno, dname
FROM emp NATURAL JOIN dept;
SELECT ename,
emp.deptno, dname
FROM emp
JOIN department
ON emp.deptno = dept.deptno
Examples of complex queries
DQL
SELECT SPECIALTY
FROM WORKERS,
WORK
WHERE WORKERS.SCHEDULE_NUMBER = JOB.SCHEDULE_NUMBER
AND OBJECT_NUMBER = 435
ALL and DISTINCT keywords
DQL
SELECT DISTINCT Country FROM Customers
Examples of complex queries
DQL
SELECT Full name
FROM WORKERS,
WORK,
OBJECTS
WHERE WORKERS.SCHEDULE_NUMBER = JOB.SCHEDULE_NUMBER
AND WORK.OBJECT_NUMBER = OBJECTS.OBJECT_NUMBER
AND OBJECT_TYPE = ' office '
Example of duplicate surnames
DISTINCT
There are no duplicate rows.
DATA GROUPING AND COMPLEX QUERIES
GROUP BY
SELECT Customers.CustomerID, COUNT (Orders.OrderID)
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
GROUP BY Customers.CustomerID
GROUP BY {column1} [, …]
DQL
HAVING
SELECT Customers.CustomerID, COUNT (Orders.OrderID)
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
GROUP BY Customers.CustomerID
HAVING COUNT (Orders.OrderID) >= 10
DQL
HAVING
SELECT OBJECT_NUMBER, MAX ( NUMBER_DAYS)
FROM WORK
WHERE START_DATE >= 20 / 10 / 01
GROUP BY OBJECT_NUMBER
HAVING COUNT ( TABLE_NUMBER) >= 2
HAVING
SELECT Student_Surname, Student_name, avg (Mark) AS AVG_Ball
FROM student NATURAL JOIN mark
GROUP BY student.idStudent
HAVING AVG_Ball > 90 ;
TOP
SELECT TOP 10 * FROM Product ORDER BY ProductName
SELECT TOP 25 PERCENT * FROM Product ORDER BY ProductName
DQL
Only in Transact-SQL
LIMIT
DQL
Only in MySQL
SELECT * FROM student LIMIT 10 ;
SELECT * FROM student LIMIT 5 offset 2 ;
Aliases
SELECT long_field_names_are_annoying AS myfield # Column alias
FROM table_name
WHERE myfield = 'Joe'
SELECT people.names, tests.score
FROM tests, really_long_people_table_name
# Table alias in MySQL
DQL
AGGREGATE FUNCTIONS
Aggregate functions
DQL
Aggregate functions
Function | Appointment |
AVG | Calculates the average |
COUNT | Counts the number of non-empty values in this column |
MAX | Calculates the largest value in a column |
MIN | Calculates the smallest value in a column |
SUM | Calculates the sum of values in a column |
ABS | Returns the absolute value of a number |
CEIL | Rounds a fractional number. |
FLOOR | Removes the fractional part of a number |
MOD | Returns the remainder when dividing one number by another |
POWER | Returns a value equal to one number raised to the power of another number |
ROUND | Rounds a number to the specified decimal place. |
DQL
Aggregate functions
Function | Appointment |
SIGN | Returns –1 if the number is negative, and 1 if it is positive |
SQRT | Calculates the square root of a number |
UPPER | Replaces all letters in a string with uppercase. |
LOWER | Replaces all letters in a string with lowercase. |
INITCAP | Capitalizes the beginning of words in a string. |
LENGTH | Calculates the number of characters in a string |
LPAD | Adds the specified character to the left of a string as many times as necessary to make the string the specified length. |
RPAD | Adds the specified character to the right of the string as many times as necessary to make the string the specified length. |
SUBSTR | Extracts a substring of the desired length from a string, starting at the specified position |
DQL
Counting lines
DQL
SELECT count(*) FROM Product ;
SELECT count(ProductName) FROM Product ;
count(*) vs count(1)
SELECT count ( * ) FROM Table_name;
SELECT count ( 1 ) FROM Table_name;
Examples of simple queries
SELECT SPECIALTY, MAX ( HOURLY_RATE)
FROM WORKERS
GROUP BY SPECIALTY
DQL
Examples of simple queries
SELECT OBJECT_NUMBER, AVG ( NUMBER_DAYS)
FROM WORK
WHERE START_DATE >= 20 / 10 / 01
GROUP BY OBJECT_NUMBER
DQL
Examples of simple queries
SELECT OBJECT_NUMBER,
MAX ( NUMBER_DAYS)
FROM WORK
WHERE START_DATE >= 20 / 10 / 01
GROUP BY OBJECT_NUMBER
HAVING COUNT ( TABLE NUMBER ) >= 2
DQL
Test
SELECT EMP_NAME,
SUM (SAL)
FROM EMPLOYEE;
Age calculation
DQL
Age calculation
SELECT name ,
birth,
CURRENT_DATE,
( YEAR (CURRENT_DATE) - YEAR (birth)) – (RIGHT(CURRENT_DATE, 5 ) < RIGHT(birth, 5 )) AS age
FROM pet
ORDER BY age;
DQL
Nested subquery
DQL
Subqueries
SELECT SPECIALTY
FROM WORKERS
WHERE LICENSE_NUMBER IN
( SELECT LICENSE_NUMBER
FROM WORK
WHERE OBJECT_NUMBER = 435 )
Nested subquery
Result of a nested subquery
Result of the entire query
DQL
Subqueries
SELECT Surname , Name
FROM Student
WHERE Ball = MAX (Ball)
SELECT Surname, Name
FROM Student
WHERE Ball = (
SELECT MAX (Ball)
FROM Student
);
DQL
SELECT
SELECT
[DISTINCT] column_names ,...
FROM table_name
[ INNER JOIN | LEFT JOIN … ] table name… ]
[ WHERE selection_conditions ]
[ GROUP BY grouping_field ]
[ HAVING grouping_conditions ]
[ ORDER BY sort_field } [ASC | DESC], ...] ;
DQL
Subqueries
SELECT
Full_name AS 'Last name' ,
Speciality AS 'Work' ,
Salary_per_hour AS 'Hourly pay'
FROM worker
WHERE Salary_per_hour > (
SELECT avg (Salary_per_hour)
FROM worker
);
DQL
Subqueries
SELECT A.NAME
FROM EMPLOYEES A
WHERE A.HOURLY_RATE >
( SELECT AVG(B.HOURLY_RATE )
FROM EMPLOYEES B
WHERE B.BRIGADIR = A.BRIGADIR)
DQL
Subqueries
SELECT name, rating
FROM restaurant_ratings
WHERE rating IN (
SELECT rating
FROM restaurant_ratings
WHERE rating > 3
AND rating < 9
)
DQL
name | rating |
The Shack | 7 |
Ribs'n'More | 5 |
name | rating |
Pizza House | 3 |
The Shack | 7 |
Arthur's | 9 |
Ribs'n'More | 5 |
Keyword ALL
SELECT name , rating
FROM restaurant_ratings
WHERE rating > ALL (
SELECT rating
FROM restaurant_ratings
WHERE rating > 3
AND rating < 9
)
DQL
name | rating |
Pizza House | 3 |
name | rating |
Pizza House | 3 |
The Shack | 7 |
Arthur's | 9 |
Ribs'n'More | 5 |
< ALL
name | rating |
The Shack | 7 |
Ribs'n'More | 5 |
Subquery result:
> ALL
name | rating |
Arthur's | 9 |
>= and <= also work
Keyword ANY
SELECT name, rating
FROM restaurant_ratings
WHERE rating > ANY (
SELECT rating
FROM restaurant_ratings
WHERE rating > 3
AND rating < 9
)
DQL
name | rating |
Pizza House | 3 |
Ribs'n'More | 5 |
name | rating |
Pizza House | 3 |
The Shack | 7 |
Arthur's | 9 |
Ribs'n'More | 5 |
< ANY
name | rating |
The Shack | 7 |
Ribs'n'More | 5 |
Subquery result:
> ANY
name | rating |
The Shack | 7 |
Arthur's | 9 |
Keyword SOME
DQL
CROSS JOIN + WHERE vs JOIN ON
DQL
SELECT *
FROM
Person ,
City
WHERE Person.CityId = City.Id
SELECT *
FROM
Person
INNER JOIN City
ON Person.CityId = City.Id
JOIN USING vs JOIN ON
DQL
Comment syntax
-- comment
/*
comment
*/
# single-line comment only in MySQL
List of key words SQL
ABSOLUTE | ACTION | ADD | ADMIN |
AFTER | AGGREGATE | ALIAS | ALL |
ALLOCATE | ALTER | AND | ANY |
ARE | ARRAY | AS | ASC |
ASSERTION | ASSERTION | AT | ATOMIC |
AUTHORIZATION | BEFORE | BEGIN | BIGINT |
BINARY | BIT | BLOB | BOOLEAN |
BOTH | BREADTH | BY | CALL |
CASCADE | CASCADED | CASE | CAST |
CATALOGUE | CHAR | CHARACTER | CHECK |
CLASS | CLOB | CLOSE | COLLATE |
COLLECTION | COLLECT | COLUMN | COMMIT |
COMPLETION | CONDITION | CONNECT | CONNECTION |
CONSTRAINT | CONSTRAINTS | CONSTRUCTOR | CONTAINS |
CONTINUE | CORRESPONDING | CREATE | CROSS |
CUBE | CURRENT | CURRENT_DATE | CURRENT_PATH |
CURRENT_ROLE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER |
CURSOR | CYCLE | DATA | DATALINK |
DATE | DAY | DEALLOCATE | DEC |
DECIMAL | DECLARE | DEFAULT | DEFERRABLE |
DELETE | DEPTH | DEREF | DESC |
DESCRIPTOR | DESTRUCTOR | DIAGNOSTICS | DICTIONARY |
DISCONNECT | DO | DOMAIN | DOUBLE |
DROP | ELEMENT | END-EXEC | EQUALS |
ESCAPE | EXCEPT | EXCEPTION | EXECUTE |
EXIT | EXPAND | EXPANDING | FALSE |
FIRST | FLOAT | FOR | FOREIGN |
FREE | FROM | FUNCTION | FUSION |
GENERAL | GET | GLOBAL | GO |
GROUP | GROUPING | HANDLER | HASH |
HOUR | IDENTITY | IF | IGNORE |
IMMEDIATELY | IN | INDICATOR | INITIALIZE |
INITIALLY | INNER | INOUT | INPUT |
INSERT | INT | INTEGER | INTERSECT |
INTERSECTION | INTERVAL | INTO | IS |
ISOLATION | ITERATE | JOIN | KEY |
LANGUAGE | LARGE | LAST | LATERAL |
LEADING | LEAVE | LEFT | LESS |
LEVEL | LIKE | LIMIT | LOCAL |
LOCALTIME | LOCALTIMESTAMP | LOCATOR | LOOP |
MATCH | MEMBER | MEETS | MERGE |
MINUTE | MODIFIES | MODIFY | MODULE |
MONTH | MULTISET | NAMES | NATIONAL |
NATURAL | NCHAR | NCLOB | NEW |
NEXT | NO | NONE | NORMALIZE |
NOT | NULL | NUMERIC | OBJECT |
OF | OFF | OLD | ON |
ONLY | OPEN | OPERATION | OPTION |
OR | ORDER | ORDINALITY | OUT |
OUTER | OUTPUT | PAD | PARAMETER |
PARAMETERS | PARTIAL | PATH | PERIOD |
POSTFIX | PRECEDES | PRECISION | PREFIX |
PREORDER | PREPARE | PRESERVE | PRIMARY |
PRIOR | PRIVILEGES | PROCEDURE | PUBLIC |
READ | READS | REAL | RECURSIVE |
REDO | REF | REFERENCES | REFERENCE |
RELATIVE | REPEAT | RESIGNATION | RESTRICTED |
RESULT | RETURN | RETURNS | REVOKE |
RIGHT | ROLE | ROLLBACK | ROLLUP |
ROUTINE | ROW | ROWS | SAVEPOINT |
SCHEMA | SCROLL | SEARCH | SECOND |
SECTION | SELECT | SEQUENCE | SESSION |
SESSION_USER | SET | SETS | SIGNAL |
SIZE | SMALLINT | SPECIFIC | SPECIFICTYPE |
SQL | SQLEXCEPTION | SQLSTATE | SQLWARNING |
START | STATE | STATIC | STRUCTURE |
SUBMULTISET | SUCCEEDS | SUM | SYSTEM_USER |
TABLE | TABLESAMPLE | TEMPORARY | TERMINATE |
THAN | THEN | TIME | TIMESTAMP |
TIMEZONE_HOUR | TIMEZONE_MINUTE | TO | TRAILING |
TRANSACTION | TRANSLATION | TREAT | TRIGGER |
TRUE | ESCAPE | UNDER | UNDO |
UNION | UNIQUE | UNKNOWN | UNTIL |
UPDATE | USAGE | USER | USING |
VALUE | VALUES | VARCHAR | VARIABLE |
VARYING | VIEW | WHEN | WHENEVER |
WHERE | WHILE | WITH | WRITE |
YEAR | ZONE | | |
Only in Transact-SQL
EXCEPT and INTERSECT
SELECT * FROM goods
EXCEPT
( SELECT * FROM goods WHERE Price > 150 )
SELECT * FROM goods WHERE Amount = 0
INTERSECT
( SELECT * FROM goods WHERE Price > 150 )
Only in Transact-SQL
SELECT
Subqueries
Let's solve a simple problem that requires comparing with the value returned from a subquery.
This example assumes that we want to request all customer order details, but we are only interested in the customer's most recent order.
SELECT
GROUP BY
Rows that have the same value in the columns specified in the list will be collected into a group.
Let's try using the GROUP BY clause to see what calculations can be performed with information about contract prices for groups of pop artists.
Text conversion
Text conversion
SELECT UCASE(D_STAFF.S_NAME) AS [UCASE(S_NAME)],
LCASE(D_STAFF.S_NAME) AS [LCASE(S_NAME)] FROM D_STAFF
Text conversion
Examples:
mysql> select LCASE('QUADRATICALLY');
-> 'quadratically'
mysql> select LOWER('QUADRATICALLY');
-> 'quadratically'
mysql> select UCASE('Hey');
-> 'HEY'
mysql> select UPPER('Hey');
-> 'HEY'
string LCASE( str string)
string LOWER ( str string) -- in MySQL
string UCASE( str string)
string UPPER ( str string) -- in MySQL
SQL .TCL
Transaction control operators
Operator | Sense | Action |
COMMIT | Complete the transaction | Complete complex interconnected information processing combined into a transaction |
ROLLBACK | Roll back transaction | Roll back changes made during a transaction |
SAVEPOINT | Save an intermediate point of transaction execution | Save the intermediate state of the database, mark it so that you can return to it |
TCL
Transactions
Transaction completion
autocommit
SET AUTOCOMMIT = 0
MySQL . Tables and Transactions
MySQL . Memory Types
Property | MyISAM | Memory | InnoDB | Archive | NDB |
Memory limitations | 256TB | RAM | 64TB | No | 384 EB |
Transactions | No | No | Yes | No | Yes |
Feature | Previously it was the default | Stores the database in RAM. Energy-dependent | Slower, but more reliable | Does not support DELETE and UPDATE. | For distributed databases |
EB = exabyte ( exabyte = 1024 * 1024 terabyte).
Setting the memory type
CREATE TABLE t (i INT ) ENGINE = INNODB;
DCL
Data management operators�
Operator | Sense | Action |
CREATE DATABASE | Create a database | Create a new database by defining the basic parameters for it |
DROP DATABASE | Delete database | Delete existing database (if you have sufficient rights ) |
ALTER DATABASE | Change database | Change the set of basic objects in the database, restrictions that apply to the entire database |
GRANT | Grant rights | Grant access rights to a number of actions on a certain database object |
REVOKE | Deprive rights | Revoke access rights to a number of actions on a certain database object |
CHANGE PASSWORD | Change password | Change password for the entire database |
DCL
GRANT
GRANT < list of powers >
ON < and ' me data or table section >
TO < user list >
GRANT READ ACCESS
ON 'Table_Estimates'
TO 'Shelepova'
DCL
REVOKE
REVOKE INSERT ON * . * FROM 'jeffrey' @ 'localhost' ;
UPDATE user SET Password = PASSWORD ( 'new_password' )
WHERE user = 'root' ;
REVOKE ALL PRIVILEGES, GRANT OPTION FROM user [, user] FLUSH PRIVILEGES;
DCL
Interview. �Beginner Programmer – SQL Basics
Interview. �Beginner programmer – basics SQL
Stored procedures �and triggers
Plan
Stored procedures
CREATE PROCEDURE procedure_name[(parameters)]
-- Procedure code
Alternative definition
Stored procedures are procedures and functions that are stored directly in the database in a compiled form and can be run by users or applications working with the database.
Advantages of stored procedures
Disadvantages of stored procedures
Stored procedures
DECLARE variable_name variable_type [(length)];
BEGIN
…
END
SET variable = value;
Stored procedures
IF condition THEN
Operator1 or Operator Group1
[ ELSE
Operator2 or Operator Group2]
END IF ;
WHILE condition DO
Operator or Operator Group
END WHILE ;
Stored Procedures . Example
CREATE DEFINER = 'root' @ 'localhost'
PROCEDURE decanat.GetMark1( in ball INT , out mark INT )
BEGIN
IF ball BETWEEN 60 AND 75 THEN
SET mark = 3;
ELSEIF ball BETWEEN 75 AND 90 THEN
SET mark = 4;
ELSEIF ball BETWEEN 90 AND 100 THEN
SET mark = 5;
ELSE SET mark = 2;
END IF;
END
Stored procedures
CREATE PROCEDURE proc_CASE( IN param1 INT )
BEGIN
DECLARE variable1 INT ;
SET variable1 = param1 + 1 ;
CASE variable1
WHEN 0 THEN
INSERT INTO table1 VALUES (param1);
WHEN 1 THEN
INSERT INTO table1 VALUES (variable1);
ELSE
INSERT INTO table1 VALUES ( 99 );
END CASE ;
END
Stored procedures
REPEAT
/*loop body*/
UNTIL condition END REPEAT
Label: LOOP
/*loop body*/
LEAVE Label; /*leave loop */
�END LOOP Tag
Selecting a separator
SELECT count(*) FROM Student;
Selecting a separator
DELIMITER ;
DELIMITER $$
SELECT * FROM user$$
MySQL
mysql > DELIMITER $$;
mysql > CREATE PROCEDURE student_data()
-> SELECT * FROM student; $$
Example of using DELIMITER
DELIMITER $$
CREATE FUNCTION `sakila` . `inventory_held_by_customer` (p_inventory_id INT ) RETURNS INT READS SQL DATA
BEGIN
DECLARE v_customer_id INT ;
DECLARE EXIT HANDLER FOR NOT FOUND RETURN NULL ;
SELECT customer_id INTO v_customer_id
FROM rental
WHERE return_date IS NULL
AND inventory_id = p_inventory_id;
RETURN v_customer_id;
END $$
DELIMITER ;
Calling a stored procedure
CALL p2();
CALL stored_procedure_name (param1, param2, ....)
CALL procedure1( 10 , 'string parameter' , @parameter_var);
Deleting a stored procedure
DROP PROCEDURE IF EXISTS p2;
Variables
CREATE PROCEDURE var_proc( IN paramstr VARCHAR ( 20 ))
BEGIN
DECLARE a, b INT DEFAULT 5 ;
DECLARE str VARCHAR ( 50 );
DECLARE today TIMESTAMP DEFAULT CURRENT_DATE;
DECLARE v1, v2, v3 TINYINT ;
� INSERT INTO table1 VALUES (a);
SET str = 'I am a string' ;
SELECT CONCAT ( str , paramstr), today
FROM table2 WHERE b >= 5 ;
END
MySQL
Saved function
CREATE [ AGGREGATE ] FUNCTION [ IF NOT EXISTS ] function_name
RETURNS { STRING | INTEGER | REAL | DECIMAL }
SONAME shared_library_name
Stored function. Example
DELIMITER //
�CREATE FUNCTION no_of_years(date1 date ) RETURNS int DETERMINISTIC
BEGIN
DECLARE date2 DATE ;
Select current_date() into date2;
RETURN year (date2) - year (date1);
END //
�DELIMITER ;
Select emp_id, fname, lname, no_of_years( start_date ) as 'years'
from employee;
Triggers
Triggers. Example
SET NEW.`Surname` = TRIM(NEW. `Surname`);
SET NEW.`Surname` = concat(upper(left(NEW.`Surname`, 1)), substr(NEW.`Surname`, 2));
Data slice (VIEW)
DDL
Data slice ( VIEW)
DDL
Data slice ( VIEW)
CREATE VIEW EMPLOYEES AS
SELECT
LICENSE_PLATE_NUMBER,
Fullname,
SPECIALTY,
BRIGADIER
FROM WORKERS
DDL
Cursor
A cursor (in Oracle, Microsoft SQL Server) is a result set and its associated pointer to the current record, which is obtained when a query is executed.
Only in Oracle, Microsoft SQL Server
CREATE PROCEDURE `employees` . `f_p` ()
BEGIN
DECLARE id_p INT ;
DECLARE name_p TINYTEXT;
DECLARE is_end INT DEFAULT 0 ; -- end flag
/*declare a cursor for a query that selects from a table
Record ID and directory name, written in uppercase letters*/
DECLARE cur_p_name CURSOR FOR
SELECT id_project,
concat (ucase( substring (project, 1 , 1 )), substring (project, 2 ))
FROM projects;
/*declare a handler for the situation when the cursor reaches
end of the resulting table*/
DECLARE CONTINUE HANDLER FOR NOT FOUND SET is_end = 1 ;
OPEN cur_p_name;
wet: LOOP /*in a loop, read cursor data and edit records*/
FETCH cur_p_name into id_p, name_p;
IF is_end THEN LEAVE wet;
END IF ;
UPDATE projects SET project = name_p WHERE id_project = id_p;
END LOOP wet;
CLOSE cur_p_name;
END $$
SQL Injection and ACID
CRUD
Create
Insert
Retrieve
Select
Update
Update
Delete
Delete
Create
ACI D
Atomicity
Atomicity
start transaction;
UPDATE Student SET Money = Money - 100 WHERE Surname="Orlov";
UPDATE Student SET Money = Money + 100 WHERE Surname="Gasimov";
commit;
Insulation
Isolation property ( Isolation)
Transaction isolation level
Read uncommitted �(Reading uncommitted data)
Transaction 1 | Transaction 2 |
UPDATE tbl1 SET f2=f2+20 WHERE f1=1; | UPDATE tbl1 SET f2=f2+25 WHERE f1=1; |
Read committed (reading committed data)
Transaction 1 | Transaction 2 |
UPDATE tbl1 SET f2=f2+1 WHERE f1=1; | |
| SELECT f2 FROM tbl1 WHERE f1=1; |
ROLLBACK WORK; | |
Repeatable read�
Transaction 1 | Transaction 2 |
| SELECT f2 FROM tbl1 WHERE f1=1; |
UPDATE tbl1 SET f2=f2+1 WHERE f1=1; | |
COMMIT; | |
| SELECT f2 FROM tbl1 WHERE f1=1; |
Serializable
Transaction 1 | Transaction 2 |
| SELECT SUM(f2) FROM tbl1; |
INSERT INTO tbl1 (f1, f2) VALUES (15,20); | |
COMMIT; | |
| SELECT SUM(f2) FROM tbl1; |
Consistency
Classification of integrity constraints
1. By methods of implementation.
2. At the time of inspection.
3. By scope.
Limitation
Examples of integrity constraints
SQL CHECK
CREATE TABLE Persons(
ID int NOT NULL ,
LastName varchar ( 255 ) NOT NULL ,
FirstName varchar ( 255 ),
Age int CHECK (Age >= 18 )
);
DDL
SQL CHECK
CREATE TABLE Persons (
ID int NOT NULL ,
LastName varchar ( 255 ) NOT NULL ,
FirstName varchar ( 255 ),
Age int ,
City varchar ( 255 ),
CONSTRAINT CHK_Person CHECK (
Age >= 18
AND City = 'Sandnes' )
);
ALTER TABLE Persons ADD CHECK (Age >= 18 );
ALTER TABLE Persons DROP CONSTRAINT CHK_PersonAge;
DDL
SQL CHECK
CREATE TABLE Student (
Kod_stud integer NOT NULL PRIMARY KEY ,
Fam char ( 30 ) NOT NULL UNIQUE,
Address char ( 50 ),
Ball decimal CHECK (Ball > 0 ),
Form_ob char ( 10 ) CHECK (Form_ob IN ( 'Day' , 'Extracurricular' , 'Evening' )
);
DDL
Consistency
Consistency property
UPDATE Person
SET cash_account = cash_account - 100
WHERE client_surname = 'Volkov' ;
�UPDATE Person
SET cash_account = cash_account + 100
WHERE client_surname = 'Hair' ;
�COMMIT ;
Durability
ACID – transaction properties
The property of atomicity ( Atomicity )
Consistency property
Isolation property
Durability
SQL injection
SQL injection
txtUserId = getRequestString( "UserId" );
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
SQL injection. 1=1
105 OR 1 = 1
SELECT * FROM Users WHERE UserId = 105 OR 1 = 1 ;
105 ; DROP TABLE Suppliers
SQL injection protection
$stmt = $dbh -> prepare( "INSERT INTO Customers (CustomerName, Address, City) VALUES (:nam, :add, :cit)" );
$stmt -> bindParam( ':nam' , $txtNam);
$stmt -> bindParam( ':add' , $txtAdd);
$stmt -> bindParam( ':cit' , $txtCit);
$stmt -> execute ();
SELECT a. *
FROM employee a,
employee b
WHERE b.id = a.chief_id
AND a.salary > b.salary
SELECT a. *
FROM employee a
WHERE a.salary = (
SELECT max (Salary)
FROM employee b
WHERE b.department_id = a.department_id
)
SELECT department_id
FROM employee
GROUP BY department_id
HAVING count ( * ) <= 3
SELECT a. *
FROM employee a
LEFT JOIN employee b
ON (b.id = a.chief_id
AND b.department_id = a.department_id
)
WHERE b.chief_id IS NULL
WITH sum_salary AS (
SELECT department_id,
sum (Salary) Salary
FROM employee
GROUP BY department_id
)
SELECT department_id
FROM sum_salarya
WHERE a.salary = (
SELECT max (Salary)
FROM sum_salary
)
Practice
SELECT MAX (Salary) FROM Employee
WHERE Salary NOT IN ( SELECT MAX (Salary) FROM Employee);
SELECT DeptID, MAX (Salary) FROM Employee GROUP BY DeptID;
SELECT DeptName, MAX (Salary) FROM Employee e
RIGHT JOIN Department d ON e.DeptId = d.DeptID
GROUP BY DeptName;
SELECT GetDate ();
Transact-SQL :
CURRENT_DATE()
MySQL :
SELECT SYSDATE FROM DUAL;
Oracle PL/SQL :
Practice
SELECT DISTINCT EmpName FROM Employees
WHERE DOB BETWEEN '01/02/1965' AND '31/11/1970' ;
SELECT COUNT ( * ), sex FROM Employees
WHERE DOB BETWEEN '01/02/1965' AND '31/11/1970'
GROUP BY sex;
SELECT EmpName FROM Employees WHERE Salary >= 20000 ;
SELECT * FROM Employees WHERE EmpName like 'M%' ;
Practice
SELECT * FROM Employees WHERE UPPER (EmpName) like '%NOVEL%' ;
SELECT
student,
marks
FROM table
WHERE marks >
( SELECT AVG (marks) FROM table )
Practice
INSERT INTO SELECT
INSERT INTO Customers (CustomerName, City, Country) �SELECT SupplierName, City, Country FROM Suppliers;
SQL SELECT INTO
SELECT * INTO CustomersBackup2017
FROM Customers;
SELECT * INTO CustomersBackup2017 IN 'Backup.mdb'
FROM Customers;
Only in Oracle, Microsoft SQL Server
DQL
SQL CASE
SELECT OrderID, Quantity,
CASE WHEN Quantity > 30 THEN "The quantity is greater than 30"
WHEN Quantity = 30 THEN "The quantity is 30"
ELSE "The quantity is under 30"
END AS Quantity_Comparison FROM OrderDetails;
SELECT CustomerName, City, Country �FROM Customers �ORDER BY �( CASE� WHEN City IS NULL THEN Country� ELSE City �END );
DQL
Test
Test
�
Number rows in a table
SELECT
@rownum: = @rownum + 1 AS rank , t.
FROM
student t,
( SELECT @rownum: = 0 ) r;
Test
CREATE TABLE people (
id INT PRIMARY KEY ,
name VARCHAR ( 45 ) )
DELETE FROM people WHERE id >= 0
Test
Database "Computer Company"
SELECT model, speed, hd
FROM PC
WHERE price < 500 ;
Product table represents the manufacturer ( maker ), model number ( model ), and type (PC, Laptop , or Printer). The model numbers in this table are assumed to be unique across manufacturers and product types. The PC table lists the processor speed ( MHz ) , the total amount of RAM ( MB), the disk size ( GB ), the CD drive speed (e.g., '4x'), and the price ( price ). The Laptop table is similar to the PC table except that instead of the CD drive speed, it lists the screen size ( in inches). The Printer table lists for each printer model whether it is color ( color ('y' if color), the printer type ( Laser , Jet , or Matrix ) , and the price ( price) .
Database "Computer Company"
SELECT model, MAX(DISTINCT price)
FROM Printer
GROUP BY model;
SELECT model, price
FROM Printer
WHERE price =
(SELECT MAX(price) FROM Printer);
SELECT MAX(price)
FROM Printer;
SQL. Select from a table
SELECT id, datetime FROM table1
WHERE id = ( SELECT max (id) FROM table1);
SELECT id, datetime FROM table1 ORDER BY id DESC LIMIT 1
SELECT id, datetime FROM table1
WHERE id IN ( SELECT max (id) FROM table1);
Revising the Select Query I
SELECT *
FROM City
WHERE CountryCode = 'USA'
AND Population > 100000 ;
1E5
Weather Observation Station 3
SELECT DISTINCT City
FROM Station
WHERE ID % 2 = 0 ;
MOD(ID, 2)
Weather Observation Station 4
SELECT COUNT(City) - COUNT(DISTINCT City)
FROM Station;
Weather Observation Station 5
SELECT City, LENGTH (City)
FROM Station
WHERE LENGTH (City) =
( SELECT MIN ( LENGTH (City)) FROM Station)
ORDER BY City
LIMIT 1 ;
�SELECT City, LENGTH (City)
FROM Station
WHERE LENGTH (City) =
( SELECT MAX ( LENGTH (City)) FROM Station)
ORDER BY City
LIMIT 1 ;
(SELECT City, LENGTH(City)
FROM Station
WHERE LENGTH(City) =
(SELECT MIN(LENGTH(City)) FROM Station)
ORDER BY City
LIMIT 1)
UNION ALL
(SELECT City, LENGTH (City)
FROM Station
WHERE LENGTH (City) =
(SELECT MAX(LENGTH (City)) FROM Station)
ORDER BY City
LIMIT 1);
UNION ALL
What is the difference between UNION and UNION ALL?
Usage example: https://acode.com.ua/union-sql/
Weather Observation Station 6
SELECT DISTINCT City
FROM Station
WHERE City LIKE 'A%'
OR City LIKE 'E%'
OR City LIKE 'I%'
OR City LIKE 'O%'
OR City LIKE 'U%' ;
SELECT City
FROM Station
WHERE SUBSTR(City, 1 , 1 )
IN ( 'A' , 'E' , 'I' , 'O' , 'U' );
SELECT DISTINCT (City)
FROM Station
WHERE City REGEXP '^[a,e,i,o,u]'
Test
Test
Rename a column
ALTER TABLE employees
CHANGE employee_email email VARCHAR ( 45 );
Test
Test
Test
Test
Test
PIVOT and UNPIVOT
SELECT DaysToManufacture, AVG (StandardCost) AS AverageCost
FROM Production.Product
GROUP BY DaysToManufacture;
DaysToManufactureAverageCost
------------------ ------------
0 5.0885
1 223.88
2 359.1082
4 949.4105
-- Pivot table with one row and five columns
SELECT 'AverageCost' AS CostSortedByProductionDays,
[0], [1], [2], [3], [4]
FROM (
SELECT DaysToManufacture,
StandardCost
FROM Production.Product
) AS SourceTable
PIVOT (
AVG (StandardCost) FOR DaysToManufacture IN
([0], [1], [2], [3], [4])
) AS PivotTable;
CostSortedByProductionDays 0 1 2 3 4
--------------------------- ----------- ----------- ----------- ----------- -----------
AverageCost 5.0885 223.88 359.1082 NULL 949.4105
Only in Oracle, Microsoft SQL Server
DQL
Test
Test
Test
Test
Test
Test
Interview No. 2
Interview No. 2
What is the difference between COUNT(*) and COUNT(column)?
Which is better to use, joins or subqueries?
SQL
Useful links
Test
Test
Test
Test
LearnSQL
SELECT last_name, specialization FROM doctor
WHERE first_name = 'Mark' AND last_name LIKE 'D%';
LearnSQL
SELECT patient.first_name, patient.last_name, visit_date, doctor.first_name, doctor.last_name
FROM patient
INNER JOIN visit
ON patient.id = patient_id
INNER JOIN doctor
ON doctor_id = doctor.id;
LearnSQL
SELECT
E1.full_name AS employee,
E2.full_name AS manager
FROM employee E1
LEFT JOIN employee E2 ON E1.manager_id = E2.id;