SlideShare a Scribd company logo
HOW TO LEAVE THE
ORM AT HOME AND
WRITE SQL
ASSEN TOTIN
Senior Engineer R&D
MariaDB Corporation
QUICK SUMMARY
● How to stop worrying (about ORM) and start living (with SQL)
● Organising structured data
● SQL. Basic queries
● SQL. Advanced queries (multiple tables, transactions)
● MariaDB CLI
● Q & A
TO ORM
OR NOT TO ORM?
TO ORM OR NOT TO ORM?
● The big promise of ORM was to abstract the data model into objects...
● ...but you still need to define the model, only as objects instead of tables.
● You can only save by reusing models, but this means storing excessive data.
● Actual databases still speak SQL, but you lose control over it.
● Aggressive object caching needed to prevent duplicate SQL queries…
● … but it creates problems with timely invalidation on data updates.
ORGANISING
STRUCTURED DATA
STRUCTURED DATA: TABLES
● Tables are easy to understand and visualise.
● Everybody is familiar with spreadsheets; database is easily imagined as a set of
interconnected spreadsheets.
● Structured data can easily be represented as tables:
● A class becomes a table.
● Data as a table: properties become columns.
● Data as a table: instances become rows.
STRUCTURED DATA: COLUMNS
● Each column has a pre-defined data type:
● Integers: INT (32 bits), but also SMALLINT, TINYINT, MEDIUMINT, BIGINT –
all signed (default) or unsigned (with the UNSIGNED keyword).
● Floating point: FLOAT (32 bits) and DOUBLE.
● Precision arithmetic: DECIMAL(a,b).
● Strings: CHAR(x), VARCHAR(x).
● Text: TEXT, but also MEDIUMTEXT, BIGTEXT.
● Date and time: DATE, TIME, DATETIME, TIMESTAMP.
● Binary: BINARY(x),VARBINARY(x).
● Column may have a default value: DEFAULT ...
STRUCTURED DATA: NULL
● Usually each cell has a value…
● ...but sometimes we need to indicate an empty cell.
● NULL is used to denote this.
● For numbers, NULL is not zero.
● For strings, NULL is not empty string.
● Default value for each column is NULL.
● A column may be declared as NOT NULL, so NULL values will not be allowed
for it. If such column has no default value, then it is mandatory to insert value
every time.
SQL BASICS
SQL BASICS
● SQL: Structured Query Language.
● Used to manipulate data in a database: add, remove, update and query
(CRUD).
● Formalised syntax using keywords with pre-defined meaning.
● Close to human speak to make understanding easier.
● Each statement is an order to be executed.
● Each statement starts with a verb, followed by a fixed construction.
SQL BASICS: CREATE TABLE
● CREATE TABLE: create an empty table.
● Provide the table name and list of columns (name and data type for each).
● Table names are case sensitive on POSIX filesystems! Good practice: always
stick to lower case.
● Table names are often plurals (because they store multiple rows of the kind).
● Column names are not case sensitive.
● Column names are often singular (because each column stores one type of
property ).
● CREATE TABLE users (id INT, name VARCHAR(255), birthday
DATE)
SQL BASICS: INSERT
● INSERT: add a row of data to a table.
● Tell the database which table to insert in (and which columns to insert in).
● INSERT INTO users VALUES (1, ‘John Doe’, ‘1981-01-23’)
● INSERT INTO users (id, name) VALUES (2, ‘Liberty Valance’)
● Use LOAD DATA for reading batches of rows from a file.
SQL BASICS: SELECT
● SELECT: fetch one or more rows from a table.
● Tell the database which table to fetch from, which rows exactly and which
columns to return.
● SELECT (id, name) FROM users
● SELECT (id) FROM users WHERE name = ‘John Doe’
● SELECT * FROM users…
● SELECT COUNT(id) AS cnt FROM users…
● SELECT COUNT(*) AS cnt, YEAR(birthday) AS yr FROM users
GROUP BY yr ORDER BY cnt
SQL BASICS: UPDATE
● UPDATE: change the values of one or more columns in one or more rows.
● Tell the database which table to update, which rows exactly and which columns
to change to what values.
● UPDATE users SET birthday=’1980-01-23’
● UPDATE users SET birthday=’1980-01-23’ WHERE id=2
SQL BASICS: DELETE
● DELETE: remove one or more rows.
● Tell database from which table to remove rows from and which exactly.
● DELETE FROM users WHERE id=2
● Rows are only marked as deleted, not removed (so still may be read from disk).
● DELETE is inefficient (unused gaps in data files).
● DELETE FROM users
● TRUNCATE TABLE users
MARIADB CLI
MARIADB CLI
● User-friendly command-line interface to MariaDB database.
● Available on each supported OS (Windows, Linux, …).
● Can be used in interactive mode…
● … or can be scripted.
● Use command-line options on launch to specify the connection properties: host,
username, database…
MARIADB CLI
Welcome to the MariaDB monitor. Commands end with ; or g.
Your MariaDB connection id is 8
Server version: 10.3.11-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or 'h' for help. Type 'c' to clear the current input
statement.
MariaDB [(none)]>
MARIADB CLI
MariaDB [test]> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| test |
+--------------------+
4 rows in set (0.001 sec)
MARIADB CLI
MariaDB [(none)]> use test;
Database changed
MariaDB [test]> show tables;
Empty set (0.001 sec)
MARIADB CLI
MariaDB [test]> CREATE TABLE test1 (id int, txt varchar(255));
Query OK, 0 rows affected (0.012 sec)
MariaDB [test]> SHOW CREATE TABLE test1;
+--------------------------------------+
| Table | Create Table |
+--------------------------------------+
| test1 | CREATE TABLE `test1` (
`id` int(11) DEFAULT NULL,
`txt` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+--------------------------------------+
1 row in set (0.001 sec)
MARIADB CLI
MariaDB [test]> INSERT INTO test1 VALUES (1, 'some text');
Query OK, 1 row affected (0.003 sec)
MariaDB [test]> INSERT INTO test1 VALUES (2, 'other text');
Query OK, 1 row affected (0.002 sec)
MariaDB [test]> SELECT * FROM test1;
+------+------------+
| id | txt |
+------+------------+
| 1 | some text |
| 2 | other text |
+------+------------+
2 rows in set (0.000 sec)
COMPLEX
SQL QUERIES
COMPLEX SQL: JOIN
● Case: read a user’s data from one table (one row)...
● ... then read all user’s email addresses from second table (multiple rows).
● SELECT id FROM users WHERE name=’John Doe’
− 1
● SELECT email FROM emails WHERE user_id=1
COMPLEX SQL: JOIN
● Read data from two tables with one query.
● Each table should have a column with matching values.
● For each value on the left column, as many rows will be returned as there are
matching values in right column.
● SELECT users.name, users.birthday, emails.email FROM users
JOIN emails ON users.id=emails.user_id
● If values are selected from the left table, they will be repeated in each row of
the result set.
● Thus JOIN finds a cross-section of two tables, hence it is also known as INNER
JOIN.
COMPLEX SQL: INNER JOIN
id name birthday
1 John Doe 1977-07-23
2 Foo Bar 1984-02-16
3 Nice Guy 1988-09-20
user_id email
1 jd@here.con
1 jdoe@there.con
2 fb@nowhere.con
name birthday email
John Doe 1977-07-23 jd@here.con
John Doe 1977-07-23 jdoe@there.con
Foo Bar 1984-02-16 fb@nowhere.con
COMPLEX SQL: NULL
● Missing and NULL values in the right column are ignored when doing a JOIN…
● ...but in some cases we want them to appear (e.g., get the birthday even if the
user has no email).
● LEFT JOIN will consider missing or NULL values on the other side as matching
values, so it will return its full table (left) and the matching section of the second
table (right), with all missing values as NULL.
● SELECT users.name, users.birthday, emails.email FROM users
LEFT JOIN emails ON users.id=emails.user_id
● RIGHT JOIN would do the opposite, return right table and the matching section
of the left.
COMPLEX SQL: LEFT JOIN
id name birthday
1 John Doe 1977-07-23
2 Foo Bar 1984-02-16
3 Nice Guy 1988-09-20
user_id email
1 jd@here.con
1 jdoe@there.con
2 fb@nowhere.con
name birthday email
John Doe 1977-07-23 jd@here.con
John Doe 1977-07-23 jdoe@there.con
Foo Bar 1984-02-16 fb@nowhere.con
Nice Guy 1988-09-20 NULL
COMPLEX SQL: INDICES
● An index takes an existing column and saves its data in ordered fashion.
● NULL values are ignored in an index.
● When a column with an index is used for lookup, the database uses the index.
● An index may have multiple columns, one to find rows and rest to read values.
● An index (incl. multi-column) may be designated UNIQUE, so the database will
not allow insertion of a duplicate value.
● When doing JOIN, always create indices on both the left and right columns.
● PRIMARY KEY is a special index, used by to find rows for columns, not
included in other indices. The primary key is UNIQUE and cannot be NULL.
● AUTO_INCREMENT is convenient way to create a primary key in which every
new row has the value of the previous plus an increment (often 1).
COMPLEX SQL: INDICES
● CREATE TABLE users (id INT UNSIGNED NOT NULL
AUTO_INCREMENT PRIMARY KEY...)
● ALTER TABLE users ADD KEY (name)
● ALTER TABLE users ADD UNIQUE KEY (name, birthday)
COMPLEX SQL: TRANSACTIONS
● Run multiple queries in an atomic fashion (e.g., debit one bank account, credit
another).
● Only succeeds if all queries within the transaction succeed.
● On first failure, revert the whole transaction.
● Requires explicit begin and end (commit or roll-back).
● DML is transactional (if supported by storage engine: InnoDB yes, MyISAM no).
● DDL is non-transactional.
● Results from transactions are only visible to other sessions once they are
committed.
COMPLEX SQL: TRANSACTIONS
● BEGIN TRANSACTION
● UPDATE balance SET amount = amount - 100 WHERE id=123
● UPDATE balance SET amount = amount + 100 WHERE id=456
● COMMIT
COMPLEX SQL: TRANSACTIONS
● BEGIN TRANSACTION
● UPDATE balance SET amount = amount - 100 WHERE id=123
− 1 row(s) updated
● UPDATE balance SET amount = amount + 100 WHERE id=456
− 0 row(s) updated
● ROLLBACK
COMPLEX SQL: STORAGE ENGINES
● MariaDB supports multiple storage engines with different properties.
● You have the choice which one to use for each table separately.
● Mix and match tables with different storage engines in one database.
● Run cross-engine JOIN.
● InnoDB: transactional, row-level locking, works well on millions of rows.
● MyISAM: file-system consistent, but slower and with table-level locking.
● ColumnStore: distributed, columnar, for analytical workloads.
● CREATE TABLE users (…) ENGINE=InnoDB
COMPLEX SQL: CHARACTER SETS
● MariaDB supports multiple character sets.
● For each character sets, various collations are supported.
● You can set character set (and optionally, a collation) on table or column level.
● A default character set and collations are always present to use if none is
specified.
● UTF-8 is often used; MariaDB supports it up to 4 bytes deep.
● CREATE TABLE users (…) CHARACTER SET utf8mb4
COMPLEX SQL: STORED PROCEDURES
● Write some business logic inside the database.
● Each stored procedure is a set of SQL commands that run as a batch without or
with parameters.
● Allows for complex data manipulation without the need for external
programming tool or execution environment.
● Very fast as run natively by the database engine.
● MariaDB supports the industry-standard PL/SQL.
HAVE YOUR SAY!
Q&A
● Ask questions now…
● … or ask later. We are here for you!
THANK YOU!

More Related Content

PDF
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
PPTX
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PPTX
Confoo 2021 - MySQL Indexes & Histograms
PDF
M|18 Understanding the Architecture of MariaDB ColumnStore
PDF
Cassandra
PPTX
PDF
What’s New In PostgreSQL 9.3
PPTX
Vertica-Database
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
Confoo 2021 - MySQL Indexes & Histograms
M|18 Understanding the Architecture of MariaDB ColumnStore
Cassandra
What’s New In PostgreSQL 9.3
Vertica-Database

What's hot (20)

PDF
Developers’ mDay 2021: Bogdan Kecman, Oracle – MySQL nekad i sad
PDF
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
PDF
Large volume data analysis on the Typesafe Reactive Platform
PDF
M|18 PolarDB: Extending Shared-storage to MyRocks
PDF
Why PostgreSQL for Analytics Infrastructure (DW)?
PDF
Oracle 12.2 sharded database management
PPTX
M|18 Creating a Reference Architecture for High Availability at Nokia
PDF
What's New In PostgreSQL 9.4
PDF
Major features postgres 11
 
PDF
PGConf.ASIA 2019 Bali - Upcoming Features in PostgreSQL 12 - John Naylor
PPTX
PostgreSQL Database Slides
PPTX
In memory databases presentation
PDF
The art of querying – newest and advanced SQL techniques
PDF
PDF
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
PPTX
Apache spark Intro
PDF
Extending Apache Spark – Beyond Spark Session Extensions
PDF
Valerii Vasylkov Erlang. measurements and benefits.
PDF
Evolution of Spark APIs
PPT
Cassandra Data Model
Developers’ mDay 2021: Bogdan Kecman, Oracle – MySQL nekad i sad
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
Large volume data analysis on the Typesafe Reactive Platform
M|18 PolarDB: Extending Shared-storage to MyRocks
Why PostgreSQL for Analytics Infrastructure (DW)?
Oracle 12.2 sharded database management
M|18 Creating a Reference Architecture for High Availability at Nokia
What's New In PostgreSQL 9.4
Major features postgres 11
 
PGConf.ASIA 2019 Bali - Upcoming Features in PostgreSQL 12 - John Naylor
PostgreSQL Database Slides
In memory databases presentation
The art of querying – newest and advanced SQL techniques
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
Apache spark Intro
Extending Apache Spark – Beyond Spark Session Extensions
Valerii Vasylkov Erlang. measurements and benefits.
Evolution of Spark APIs
Cassandra Data Model
Ad

Similar to How to leave the ORM at home and write SQL (20)

PDF
Database Design most common pitfalls
PDF
SQL Overview
PPTX
Crime record management system project.pptx
PDF
Rdbms day3
DOCX
Sql interview questions
PDF
Use Your MySQL Knowledge to Become an Instant Cassandra Guru
PPTX
PDF
MySQL Query Optimisation 101
PDF
Advanced MariaDB features that developers love.pdf
PPT
dbs class 7.ppt
PDF
Sql overview-1232931296681161-1
PDF
Changing your huge table's data types in production
PPTX
Dbms & oracle
PDF
MariaDB 10.11 key features overview for DBAs
PPTX
ADVANCE ITT BY PRASAD
PDF
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
PDF
RDBMS SQL Basics
PPT
UNIT2.ppt
PPTX
SQL Server Select Topics
Database Design most common pitfalls
SQL Overview
Crime record management system project.pptx
Rdbms day3
Sql interview questions
Use Your MySQL Knowledge to Become an Instant Cassandra Guru
MySQL Query Optimisation 101
Advanced MariaDB features that developers love.pdf
dbs class 7.ppt
Sql overview-1232931296681161-1
Changing your huge table's data types in production
Dbms & oracle
MariaDB 10.11 key features overview for DBAs
ADVANCE ITT BY PRASAD
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
RDBMS SQL Basics
UNIT2.ppt
SQL Server Select Topics
Ad

More from MariaDB plc (20)

PDF
MariaDB Berlin Roadshow Slides - 8 April 2025
PDF
MariaDB München Roadshow - 24 September, 2024
PDF
MariaDB Paris Roadshow - 19 September 2024
PDF
MariaDB Amsterdam Roadshow: 19 September, 2024
PDF
MariaDB Paris Workshop 2023 - MaxScale 23.02.x
PDF
MariaDB Paris Workshop 2023 - Newpharma
PDF
MariaDB Paris Workshop 2023 - Cloud
PDF
MariaDB Paris Workshop 2023 - MariaDB Enterprise
PDF
MariaDB Paris Workshop 2023 - Performance Optimization
PDF
MariaDB Paris Workshop 2023 - MaxScale
PDF
MariaDB Paris Workshop 2023 - novadys presentation
PDF
MariaDB Paris Workshop 2023 - DARVA presentation
PDF
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server
PDF
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-Backup
PDF
Einführung : MariaDB Tech und Business Update Hamburg 2023
PDF
Hochverfügbarkeitslösungen mit MariaDB
PDF
Die Neuheiten in MariaDB Enterprise Server
PDF
Global Data Replication with Galera for Ansell Guardian®
PDF
Introducing workload analysis
PDF
Under the hood: SkySQL monitoring
MariaDB Berlin Roadshow Slides - 8 April 2025
MariaDB München Roadshow - 24 September, 2024
MariaDB Paris Roadshow - 19 September 2024
MariaDB Amsterdam Roadshow: 19 September, 2024
MariaDB Paris Workshop 2023 - MaxScale 23.02.x
MariaDB Paris Workshop 2023 - Newpharma
MariaDB Paris Workshop 2023 - Cloud
MariaDB Paris Workshop 2023 - MariaDB Enterprise
MariaDB Paris Workshop 2023 - Performance Optimization
MariaDB Paris Workshop 2023 - MaxScale
MariaDB Paris Workshop 2023 - novadys presentation
MariaDB Paris Workshop 2023 - DARVA presentation
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-Backup
Einführung : MariaDB Tech und Business Update Hamburg 2023
Hochverfügbarkeitslösungen mit MariaDB
Die Neuheiten in MariaDB Enterprise Server
Global Data Replication with Galera for Ansell Guardian®
Introducing workload analysis
Under the hood: SkySQL monitoring

Recently uploaded (20)

PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
System and Network Administraation Chapter 3
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Digital Strategies for Manufacturing Companies
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
VVF-Customer-Presentation2025-Ver1.9.pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 41
System and Network Administraation Chapter 3
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
2025 Textile ERP Trends: SAP, Odoo & Oracle
How to Choose the Right IT Partner for Your Business in Malaysia
Design an Analysis of Algorithms I-SECS-1021-03
How Creative Agencies Leverage Project Management Software.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Digital Strategies for Manufacturing Companies
Upgrade and Innovation Strategies for SAP ERP Customers
Understanding Forklifts - TECH EHS Solution
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Navsoft: AI-Powered Business Solutions & Custom Software Development
PTS Company Brochure 2025 (1).pdf.......
CHAPTER 2 - PM Management and IT Context
Which alternative to Crystal Reports is best for small or large businesses.pdf

How to leave the ORM at home and write SQL

  • 1. HOW TO LEAVE THE ORM AT HOME AND WRITE SQL ASSEN TOTIN Senior Engineer R&D MariaDB Corporation
  • 2. QUICK SUMMARY ● How to stop worrying (about ORM) and start living (with SQL) ● Organising structured data ● SQL. Basic queries ● SQL. Advanced queries (multiple tables, transactions) ● MariaDB CLI ● Q & A
  • 3. TO ORM OR NOT TO ORM?
  • 4. TO ORM OR NOT TO ORM? ● The big promise of ORM was to abstract the data model into objects... ● ...but you still need to define the model, only as objects instead of tables. ● You can only save by reusing models, but this means storing excessive data. ● Actual databases still speak SQL, but you lose control over it. ● Aggressive object caching needed to prevent duplicate SQL queries… ● … but it creates problems with timely invalidation on data updates.
  • 6. STRUCTURED DATA: TABLES ● Tables are easy to understand and visualise. ● Everybody is familiar with spreadsheets; database is easily imagined as a set of interconnected spreadsheets. ● Structured data can easily be represented as tables: ● A class becomes a table. ● Data as a table: properties become columns. ● Data as a table: instances become rows.
  • 7. STRUCTURED DATA: COLUMNS ● Each column has a pre-defined data type: ● Integers: INT (32 bits), but also SMALLINT, TINYINT, MEDIUMINT, BIGINT – all signed (default) or unsigned (with the UNSIGNED keyword). ● Floating point: FLOAT (32 bits) and DOUBLE. ● Precision arithmetic: DECIMAL(a,b). ● Strings: CHAR(x), VARCHAR(x). ● Text: TEXT, but also MEDIUMTEXT, BIGTEXT. ● Date and time: DATE, TIME, DATETIME, TIMESTAMP. ● Binary: BINARY(x),VARBINARY(x). ● Column may have a default value: DEFAULT ...
  • 8. STRUCTURED DATA: NULL ● Usually each cell has a value… ● ...but sometimes we need to indicate an empty cell. ● NULL is used to denote this. ● For numbers, NULL is not zero. ● For strings, NULL is not empty string. ● Default value for each column is NULL. ● A column may be declared as NOT NULL, so NULL values will not be allowed for it. If such column has no default value, then it is mandatory to insert value every time.
  • 10. SQL BASICS ● SQL: Structured Query Language. ● Used to manipulate data in a database: add, remove, update and query (CRUD). ● Formalised syntax using keywords with pre-defined meaning. ● Close to human speak to make understanding easier. ● Each statement is an order to be executed. ● Each statement starts with a verb, followed by a fixed construction.
  • 11. SQL BASICS: CREATE TABLE ● CREATE TABLE: create an empty table. ● Provide the table name and list of columns (name and data type for each). ● Table names are case sensitive on POSIX filesystems! Good practice: always stick to lower case. ● Table names are often plurals (because they store multiple rows of the kind). ● Column names are not case sensitive. ● Column names are often singular (because each column stores one type of property ). ● CREATE TABLE users (id INT, name VARCHAR(255), birthday DATE)
  • 12. SQL BASICS: INSERT ● INSERT: add a row of data to a table. ● Tell the database which table to insert in (and which columns to insert in). ● INSERT INTO users VALUES (1, ‘John Doe’, ‘1981-01-23’) ● INSERT INTO users (id, name) VALUES (2, ‘Liberty Valance’) ● Use LOAD DATA for reading batches of rows from a file.
  • 13. SQL BASICS: SELECT ● SELECT: fetch one or more rows from a table. ● Tell the database which table to fetch from, which rows exactly and which columns to return. ● SELECT (id, name) FROM users ● SELECT (id) FROM users WHERE name = ‘John Doe’ ● SELECT * FROM users… ● SELECT COUNT(id) AS cnt FROM users… ● SELECT COUNT(*) AS cnt, YEAR(birthday) AS yr FROM users GROUP BY yr ORDER BY cnt
  • 14. SQL BASICS: UPDATE ● UPDATE: change the values of one or more columns in one or more rows. ● Tell the database which table to update, which rows exactly and which columns to change to what values. ● UPDATE users SET birthday=’1980-01-23’ ● UPDATE users SET birthday=’1980-01-23’ WHERE id=2
  • 15. SQL BASICS: DELETE ● DELETE: remove one or more rows. ● Tell database from which table to remove rows from and which exactly. ● DELETE FROM users WHERE id=2 ● Rows are only marked as deleted, not removed (so still may be read from disk). ● DELETE is inefficient (unused gaps in data files). ● DELETE FROM users ● TRUNCATE TABLE users
  • 17. MARIADB CLI ● User-friendly command-line interface to MariaDB database. ● Available on each supported OS (Windows, Linux, …). ● Can be used in interactive mode… ● … or can be scripted. ● Use command-line options on launch to specify the connection properties: host, username, database…
  • 18. MARIADB CLI Welcome to the MariaDB monitor. Commands end with ; or g. Your MariaDB connection id is 8 Server version: 10.3.11-MariaDB MariaDB Server Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Type 'help;' or 'h' for help. Type 'c' to clear the current input statement. MariaDB [(none)]>
  • 19. MARIADB CLI MariaDB [test]> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | test | +--------------------+ 4 rows in set (0.001 sec)
  • 20. MARIADB CLI MariaDB [(none)]> use test; Database changed MariaDB [test]> show tables; Empty set (0.001 sec)
  • 21. MARIADB CLI MariaDB [test]> CREATE TABLE test1 (id int, txt varchar(255)); Query OK, 0 rows affected (0.012 sec) MariaDB [test]> SHOW CREATE TABLE test1; +--------------------------------------+ | Table | Create Table | +--------------------------------------+ | test1 | CREATE TABLE `test1` ( `id` int(11) DEFAULT NULL, `txt` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 | +--------------------------------------+ 1 row in set (0.001 sec)
  • 22. MARIADB CLI MariaDB [test]> INSERT INTO test1 VALUES (1, 'some text'); Query OK, 1 row affected (0.003 sec) MariaDB [test]> INSERT INTO test1 VALUES (2, 'other text'); Query OK, 1 row affected (0.002 sec) MariaDB [test]> SELECT * FROM test1; +------+------------+ | id | txt | +------+------------+ | 1 | some text | | 2 | other text | +------+------------+ 2 rows in set (0.000 sec)
  • 24. COMPLEX SQL: JOIN ● Case: read a user’s data from one table (one row)... ● ... then read all user’s email addresses from second table (multiple rows). ● SELECT id FROM users WHERE name=’John Doe’ − 1 ● SELECT email FROM emails WHERE user_id=1
  • 25. COMPLEX SQL: JOIN ● Read data from two tables with one query. ● Each table should have a column with matching values. ● For each value on the left column, as many rows will be returned as there are matching values in right column. ● SELECT users.name, users.birthday, emails.email FROM users JOIN emails ON users.id=emails.user_id ● If values are selected from the left table, they will be repeated in each row of the result set. ● Thus JOIN finds a cross-section of two tables, hence it is also known as INNER JOIN.
  • 26. COMPLEX SQL: INNER JOIN id name birthday 1 John Doe 1977-07-23 2 Foo Bar 1984-02-16 3 Nice Guy 1988-09-20 user_id email 1 jd@here.con 1 jdoe@there.con 2 fb@nowhere.con name birthday email John Doe 1977-07-23 jd@here.con John Doe 1977-07-23 jdoe@there.con Foo Bar 1984-02-16 fb@nowhere.con
  • 27. COMPLEX SQL: NULL ● Missing and NULL values in the right column are ignored when doing a JOIN… ● ...but in some cases we want them to appear (e.g., get the birthday even if the user has no email). ● LEFT JOIN will consider missing or NULL values on the other side as matching values, so it will return its full table (left) and the matching section of the second table (right), with all missing values as NULL. ● SELECT users.name, users.birthday, emails.email FROM users LEFT JOIN emails ON users.id=emails.user_id ● RIGHT JOIN would do the opposite, return right table and the matching section of the left.
  • 28. COMPLEX SQL: LEFT JOIN id name birthday 1 John Doe 1977-07-23 2 Foo Bar 1984-02-16 3 Nice Guy 1988-09-20 user_id email 1 jd@here.con 1 jdoe@there.con 2 fb@nowhere.con name birthday email John Doe 1977-07-23 jd@here.con John Doe 1977-07-23 jdoe@there.con Foo Bar 1984-02-16 fb@nowhere.con Nice Guy 1988-09-20 NULL
  • 29. COMPLEX SQL: INDICES ● An index takes an existing column and saves its data in ordered fashion. ● NULL values are ignored in an index. ● When a column with an index is used for lookup, the database uses the index. ● An index may have multiple columns, one to find rows and rest to read values. ● An index (incl. multi-column) may be designated UNIQUE, so the database will not allow insertion of a duplicate value. ● When doing JOIN, always create indices on both the left and right columns. ● PRIMARY KEY is a special index, used by to find rows for columns, not included in other indices. The primary key is UNIQUE and cannot be NULL. ● AUTO_INCREMENT is convenient way to create a primary key in which every new row has the value of the previous plus an increment (often 1).
  • 30. COMPLEX SQL: INDICES ● CREATE TABLE users (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY...) ● ALTER TABLE users ADD KEY (name) ● ALTER TABLE users ADD UNIQUE KEY (name, birthday)
  • 31. COMPLEX SQL: TRANSACTIONS ● Run multiple queries in an atomic fashion (e.g., debit one bank account, credit another). ● Only succeeds if all queries within the transaction succeed. ● On first failure, revert the whole transaction. ● Requires explicit begin and end (commit or roll-back). ● DML is transactional (if supported by storage engine: InnoDB yes, MyISAM no). ● DDL is non-transactional. ● Results from transactions are only visible to other sessions once they are committed.
  • 32. COMPLEX SQL: TRANSACTIONS ● BEGIN TRANSACTION ● UPDATE balance SET amount = amount - 100 WHERE id=123 ● UPDATE balance SET amount = amount + 100 WHERE id=456 ● COMMIT
  • 33. COMPLEX SQL: TRANSACTIONS ● BEGIN TRANSACTION ● UPDATE balance SET amount = amount - 100 WHERE id=123 − 1 row(s) updated ● UPDATE balance SET amount = amount + 100 WHERE id=456 − 0 row(s) updated ● ROLLBACK
  • 34. COMPLEX SQL: STORAGE ENGINES ● MariaDB supports multiple storage engines with different properties. ● You have the choice which one to use for each table separately. ● Mix and match tables with different storage engines in one database. ● Run cross-engine JOIN. ● InnoDB: transactional, row-level locking, works well on millions of rows. ● MyISAM: file-system consistent, but slower and with table-level locking. ● ColumnStore: distributed, columnar, for analytical workloads. ● CREATE TABLE users (…) ENGINE=InnoDB
  • 35. COMPLEX SQL: CHARACTER SETS ● MariaDB supports multiple character sets. ● For each character sets, various collations are supported. ● You can set character set (and optionally, a collation) on table or column level. ● A default character set and collations are always present to use if none is specified. ● UTF-8 is often used; MariaDB supports it up to 4 bytes deep. ● CREATE TABLE users (…) CHARACTER SET utf8mb4
  • 36. COMPLEX SQL: STORED PROCEDURES ● Write some business logic inside the database. ● Each stored procedure is a set of SQL commands that run as a batch without or with parameters. ● Allows for complex data manipulation without the need for external programming tool or execution environment. ● Very fast as run natively by the database engine. ● MariaDB supports the industry-standard PL/SQL.
  • 38. Q&A ● Ask questions now… ● … or ask later. We are here for you!

Editor's Notes

  • #2: Note that DB in MariaDB is not bolded