8. SQL - Structured Query Language
CREATE TABLE student(id INT, first_name VARCHAR(25), last_name VARCHAR(25),
email VARCHAR(100), PRIMARY KEY (id));
INSERT INTO student VALUES (1, 'John', 'Peterson', 'jpeterson@email');
SELECT * FROM student;
SQL WIKI tutorial
9. SQL
SELECT * FROM student s JOIN student_course sc ON s.id = sc.student_id JOIN
course c ON sc.course_id = c.id WHERE c.mentor_id = 3;
SELECT s.id, s.first_name, s.last_name, c.id, c.title FROM student s JOIN
student_course sc ON s.id = sc.student_id JOIN course c ON sc.course_id = c.id
WHERE c.mentor_id = 3 ORDER BY s.id;
10.
11. Indexes
Індекс (англ. index) — об'єкт бази даних, що створений з метою підвищення ефективності виконання запитів. Таблиці в базі
даних можуть мати велику кількість рядків, які зберігаються у довільному порядку, і їх пошук за заданим значенням шляхом
послідовного перегляду таблиці рядок за рядком може займати багато часу. Індекс формується зі значень одного чи кількох
стовпчиків таблиці і вказівників на відповідні рядки таблиці і, таким чином, дозволяє знаходити потрібний рядок за заданим
значенням. Прискорення роботи з використанням індексів досягається в першу чергу за рахунок того, що індекс має структуру,
що оптимізована для пошуку — наприклад, збалансованого дерева. Деякі СКБД розширюють можливості індексів введенням
можливості створення індексів за виразами. Наприклад, індекс може бути створений за виразом upper(last_name) і відповідно
буде зберігати посилання, ключем яких будуть значення поля last_name в верхньому регістрі. Крім цього, індекси можуть бути
оголошенні як унікальні так і не унікальні. Унікальний індекс реалізує обмеження цілісності на таблиці, виключаючи можливість
вставки значень, що повторюються.
12. Transactions
Транза́кція (англ. transaction) — група послідовних операцій з базою даних, яка є логічною одиницею роботи з даними.
Транзакція може бути виконана або цілком і успішно, дотримуючись цілісності даних і незалежно від інших транзакцій, що
йдуть паралельно, або не виконана зовсім, і тоді вона не може справити ніякого ефекту. Транзакції оброблюються
транзакційними системами, в процесі роботи яких створюється історія транзакцій. Транзакції з базою даних використовуються
для забезпечення прінципів ACID:
● Atomicity (атомарність) - гарантує, що жодна транзакція не буде виконана частково. Будуть або виконані всі операції,
що беруть участь у транзакції, або не виконано жодної. Якщо протягом роботи однієї з операцій виникне помилка і
операцію буде відхилено, то будуть відхилені також усі інші зміни, здійснені в межах транзакції.
● Consistency (узгодженість) - Відповідно до вимоги узгодженості (англ. Consistency), система повинна перебувати в
узгодженому, несуперечливому стані до початку дії транзакції і по її завершенню. При цьому вона може перебувати в
неузгодженому стані протягом виконання транзакції, проте ця неузгодженість завдяки іншим властивостям —
атомарності та ізольованості — не буде видимою за межами транзакції.
● Isolation (ізольованість) - означає, що жодні проміжні зміни не будуть видимі за межами транзакції аж до її завершення.
Питання ізоляції стає актуальним при одночасній роботі багатьох транзакцій з одними й тими самими даними. Згідно з
цією вимогою, якщо дві транзакції намагатимуться змінити одні й ті самі дані, то одну з них буде відхилено або
призупинено до завершення другої.
● Durability (стійкість) - гарантує, що незалежно від інших проблем після відновлення працездатності системи результати
завершених транзакцій будуть збережені. Іншими словами, якщо користувач отримав повідомлення про успішне
завершення транзакції, то він може бути впевнений, що дані будуть збережені та відновлені у випадку збоїв.
13. Pros
● Relational databases are well-documented
and mature technologies, and RDBMS are
sold and maintained by a number of
established corporations.
● SQL standards are well-defined and
commonly accepted.
● A large pool of qualified developers have
experience with SQL and RDBMS.
● All RDBMS are ACID-compliant, meaning
they satisfy the requirements of Atomicity,
Consistency, Isolation, and Durability.
● RDBMSes don’t work well — or at all — with
unstructured or semi-structured data, due to
schema and type constraints. This makes them
ill-suited for large analytics or IoT event loads.
● The tables in your relational database will not
necessarily map one-to-one with an object or
class representing the same data.
● When migrating one RDBMS to another,
schemas and types must generally be identical
between source and destination tables for
migration to work (schema constraint). For many
of the same reasons, extremely complex datasets
or those containing variable-length records are
generally difficult to handle with an RDBMS
schema.
Cons
15. Key-Value Stores
such as Redis and Amazon DynamoDB, are extremely simple database management systems that store only key-value
pairs and provide basic functionality for retrieving the value associated with a known key.
The simplicity of key-value stores makes these database management systems particularly well-suited to embedded
databases, where the stored data is not particularly complex and speed is of paramount importance.
16. Column Stores
such as Cassandra, Scylla, and HBase, are schema-agnostic systems that enable users to store data in column families or tables, a
single row of which can be thought of as a record — a multi-dimensional key-value store.
These solutions are designed with the goal of scaling well enough to manage petabytes of data across as many as thousands of
commodity servers in a massive, distributed system.
Although technically schema-free, wide column stores like Scylla and Cassandra use an SQL variant called CQL for data definition and
manipulation, making them straightforward to those already familiar with RDBMS.
17. Document Stores
including MongoDB and Couchbase, are schema-free
systems that store data in the form of JSON documents.
Document stores are similar to key-value or wide column
stores, but the document name is the key and the contents of
the document, whatever they are, are the value.
In a document store, individual records do not require a
uniform structure, can contain many different value types, and
can be nested. This flexibility makes them particularly well-
suited to manage semi-structured data across distributed
systems.
18. Graph Databases
such as Neo4J and Datastax Enterprise Graph, represent
data as a network of related nodes or objects in order to
facilitate data visualizations and graph analytics.
A node or object in a graph database contains free-form data
that is connected by relationships and grouped according to
labels. Graph-Oriented Database Management Systems
(DBMS) software is designed with an emphasis on illustrating
connections between data points.
As a result, graph databases are typically used when analysis
of the relationships between heterogeneous data points is the
end goal of the system, such as in fraud prevention,
advanced enterprise operations, or Facebook’s original
friends graph.
19. Search engines
such as Elasticsearch, Splunk, and Solr, store data using schema-free JSON documents. They are similar to document stores, but with
a greater emphasis on making your unstructured or semi-structured data easily accessible via text-based searches with strings of
varying complexity.
20. MongoDB
MongoDB uses JSON-like documents with schemata. MongoDB is developed by MongoDB Inc., and is published under a combination
of the Server Side Public License and the Apache License.
Read more