SlideShare ist ein Scribd-Unternehmen logo
1 von 39
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!

Weitere ähnliche Inhalte

Was ist angesagt?

Developers’ mDay 2021: Bogdan Kecman, Oracle – MySQL nekad i sad
Developers’ mDay 2021: Bogdan Kecman, Oracle – MySQL nekad i sadDevelopers’ mDay 2021: Bogdan Kecman, Oracle – MySQL nekad i sad
Developers’ mDay 2021: Bogdan Kecman, Oracle – MySQL nekad i sadmCloud
 
Ten Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLTen Reasons Why You Should Prefer PostgreSQL to MySQL
Ten Reasons Why You Should Prefer PostgreSQL to MySQLanandology
 
Large volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformLarge volume data analysis on the Typesafe Reactive Platform
Large volume data analysis on the Typesafe Reactive PlatformMartin Zapletal
 
M|18 PolarDB: Extending Shared-storage to MyRocks
M|18 PolarDB: Extending Shared-storage to MyRocksM|18 PolarDB: Extending Shared-storage to MyRocks
M|18 PolarDB: Extending Shared-storage to MyRocksMariaDB plc
 
Why PostgreSQL for Analytics Infrastructure (DW)?
Why PostgreSQL for Analytics Infrastructure (DW)?Why PostgreSQL for Analytics Infrastructure (DW)?
Why PostgreSQL for Analytics Infrastructure (DW)?Huy Nguyen
 
Oracle 12.2 sharded database management
Oracle 12.2 sharded database managementOracle 12.2 sharded database management
Oracle 12.2 sharded database managementLeyi (Kamus) Zhang
 
M|18 Creating a Reference Architecture for High Availability at Nokia
M|18 Creating a Reference Architecture for High Availability at NokiaM|18 Creating a Reference Architecture for High Availability at Nokia
M|18 Creating a Reference Architecture for High Availability at NokiaMariaDB plc
 
What's New In PostgreSQL 9.4
What's New In PostgreSQL 9.4What's New In PostgreSQL 9.4
What's New In PostgreSQL 9.4Pavan Deolasee
 
Major features postgres 11
Major features postgres 11Major features postgres 11
Major features postgres 11EDB
 
PGConf.ASIA 2019 Bali - Upcoming Features in PostgreSQL 12 - John Naylor
PGConf.ASIA 2019 Bali - Upcoming Features in PostgreSQL 12 - John NaylorPGConf.ASIA 2019 Bali - Upcoming Features in PostgreSQL 12 - John Naylor
PGConf.ASIA 2019 Bali - Upcoming Features in PostgreSQL 12 - John NaylorEqunix Business Solutions
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slidesmetsarin
 
In memory databases presentation
In memory databases presentationIn memory databases presentation
In memory databases presentationMichael Keane
 
The art of querying – newest and advanced SQL techniques
The art of querying – newest and advanced SQL techniquesThe art of querying – newest and advanced SQL techniques
The art of querying – newest and advanced SQL techniquesZohar Elkayam
 
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014
MySQL Query Tuning for the Squeemish -- Fossetcon Orlando Sep 2014Dave Stokes
 
Extending Apache Spark – Beyond Spark Session Extensions
Extending Apache Spark – Beyond Spark Session ExtensionsExtending Apache Spark – Beyond Spark Session Extensions
Extending Apache Spark – Beyond Spark Session ExtensionsDatabricks
 
Valerii Vasylkov Erlang. measurements and benefits.
Valerii Vasylkov Erlang. measurements and benefits.Valerii Vasylkov Erlang. measurements and benefits.
Valerii Vasylkov Erlang. measurements and benefits.Аліна Шепшелей
 
Cassandra Data Model
Cassandra Data ModelCassandra Data Model
Cassandra Data Modelebenhewitt
 

Was ist angesagt? (20)

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

Ähnlich wie How to leave the ORM at home and write SQL

Database Design most common pitfalls
Database Design most common pitfallsDatabase Design most common pitfalls
Database Design most common pitfallsFederico Razzoli
 
Sql interview questions
Sql interview questionsSql interview questions
Sql interview questionsnagesh Rao
 
Use Your MySQL Knowledge to Become an Instant Cassandra Guru
Use Your MySQL Knowledge to Become an Instant Cassandra GuruUse Your MySQL Knowledge to Become an Instant Cassandra Guru
Use Your MySQL Knowledge to Become an Instant Cassandra GuruTim Callaghan
 
MySQL Query Optimisation 101
MySQL Query Optimisation 101MySQL Query Optimisation 101
MySQL Query Optimisation 101Federico Razzoli
 
Advanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfAdvanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfFederico Razzoli
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.pptMARasheed3
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1sagaroceanic11
 
Changing your huge table's data types in production
Changing your huge table's data types in productionChanging your huge table's data types in production
Changing your huge table's data types in productionJimmy Angelakos
 
MariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsMariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsFederico Razzoli
 
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)Valerii Kravchuk
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select TopicsJay Coskey
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowPavithSingh
 

Ähnlich wie How to leave the ORM at home and write SQL (20)

Database Design most common pitfalls
Database Design most common pitfallsDatabase Design most common pitfalls
Database Design most common pitfalls
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Rdbms day3
Rdbms day3Rdbms day3
Rdbms day3
 
Sql interview questions
Sql interview questionsSql interview questions
Sql interview questions
 
Use Your MySQL Knowledge to Become an Instant Cassandra Guru
Use Your MySQL Knowledge to Become an Instant Cassandra GuruUse Your MySQL Knowledge to Become an Instant Cassandra Guru
Use Your MySQL Knowledge to Become an Instant Cassandra Guru
 
Database
Database Database
Database
 
MySQL Query Optimisation 101
MySQL Query Optimisation 101MySQL Query Optimisation 101
MySQL Query Optimisation 101
 
Advanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdfAdvanced MariaDB features that developers love.pdf
Advanced MariaDB features that developers love.pdf
 
dbs class 7.ppt
dbs class 7.pptdbs class 7.ppt
dbs class 7.ppt
 
Sql overview-1232931296681161-1
Sql overview-1232931296681161-1Sql overview-1232931296681161-1
Sql overview-1232931296681161-1
 
Changing your huge table's data types in production
Changing your huge table's data types in productionChanging your huge table's data types in production
Changing your huge table's data types in production
 
Dbms & oracle
Dbms & oracleDbms & oracle
Dbms & oracle
 
MariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAsMariaDB 10.11 key features overview for DBAs
MariaDB 10.11 key features overview for DBAs
 
ADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASADADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASAD
 
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
Instant add column for inno db in mariadb 10.3+ (fosdem 2018, second draft)
 
SQL
SQLSQL
SQL
 
RDBMS SQL Basics
RDBMS SQL BasicsRDBMS SQL Basics
RDBMS SQL Basics
 
UNIT2.ppt
UNIT2.pptUNIT2.ppt
UNIT2.ppt
 
SQL Server Select Topics
SQL Server Select TopicsSQL Server Select Topics
SQL Server Select Topics
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 

Mehr von MariaDB plc

MariaDB Paris Workshop 2023 - MaxScale 23.02.x
MariaDB Paris Workshop 2023 - MaxScale 23.02.xMariaDB Paris Workshop 2023 - MaxScale 23.02.x
MariaDB Paris Workshop 2023 - MaxScale 23.02.xMariaDB plc
 
MariaDB Paris Workshop 2023 - Newpharma
MariaDB Paris Workshop 2023 - NewpharmaMariaDB Paris Workshop 2023 - Newpharma
MariaDB Paris Workshop 2023 - NewpharmaMariaDB plc
 
MariaDB Paris Workshop 2023 - Cloud
MariaDB Paris Workshop 2023 - CloudMariaDB Paris Workshop 2023 - Cloud
MariaDB Paris Workshop 2023 - CloudMariaDB plc
 
MariaDB Paris Workshop 2023 - MariaDB Enterprise
MariaDB Paris Workshop 2023 - MariaDB EnterpriseMariaDB Paris Workshop 2023 - MariaDB Enterprise
MariaDB Paris Workshop 2023 - MariaDB EnterpriseMariaDB plc
 
MariaDB Paris Workshop 2023 - Performance Optimization
MariaDB Paris Workshop 2023 - Performance OptimizationMariaDB Paris Workshop 2023 - Performance Optimization
MariaDB Paris Workshop 2023 - Performance OptimizationMariaDB plc
 
MariaDB Paris Workshop 2023 - MaxScale
MariaDB Paris Workshop 2023 - MaxScale MariaDB Paris Workshop 2023 - MaxScale
MariaDB Paris Workshop 2023 - MaxScale MariaDB plc
 
MariaDB Paris Workshop 2023 - novadys presentation
MariaDB Paris Workshop 2023 - novadys presentationMariaDB Paris Workshop 2023 - novadys presentation
MariaDB Paris Workshop 2023 - novadys presentationMariaDB plc
 
MariaDB Paris Workshop 2023 - DARVA presentation
MariaDB Paris Workshop 2023 - DARVA presentationMariaDB Paris Workshop 2023 - DARVA presentation
MariaDB Paris Workshop 2023 - DARVA presentationMariaDB plc
 
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server MariaDB plc
 
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-Backup
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-BackupMariaDB SkySQL Autonome Skalierung, Observability, Cloud-Backup
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-BackupMariaDB plc
 
Einführung : MariaDB Tech und Business Update Hamburg 2023
Einführung : MariaDB Tech und Business Update Hamburg 2023Einführung : MariaDB Tech und Business Update Hamburg 2023
Einführung : MariaDB Tech und Business Update Hamburg 2023MariaDB plc
 
Hochverfügbarkeitslösungen mit MariaDB
Hochverfügbarkeitslösungen mit MariaDBHochverfügbarkeitslösungen mit MariaDB
Hochverfügbarkeitslösungen mit MariaDBMariaDB plc
 
Die Neuheiten in MariaDB Enterprise Server
Die Neuheiten in MariaDB Enterprise ServerDie Neuheiten in MariaDB Enterprise Server
Die Neuheiten in MariaDB Enterprise ServerMariaDB plc
 
Global Data Replication with Galera for Ansell Guardian®
Global Data Replication with Galera for Ansell Guardian®Global Data Replication with Galera for Ansell Guardian®
Global Data Replication with Galera for Ansell Guardian®MariaDB plc
 
Introducing workload analysis
Introducing workload analysisIntroducing workload analysis
Introducing workload analysisMariaDB plc
 
Under the hood: SkySQL monitoring
Under the hood: SkySQL monitoringUnder the hood: SkySQL monitoring
Under the hood: SkySQL monitoringMariaDB plc
 
Introducing the R2DBC async Java connector
Introducing the R2DBC async Java connectorIntroducing the R2DBC async Java connector
Introducing the R2DBC async Java connectorMariaDB plc
 
MariaDB Enterprise Tools introduction
MariaDB Enterprise Tools introductionMariaDB Enterprise Tools introduction
MariaDB Enterprise Tools introductionMariaDB plc
 
Faster, better, stronger: The new InnoDB
Faster, better, stronger: The new InnoDBFaster, better, stronger: The new InnoDB
Faster, better, stronger: The new InnoDBMariaDB plc
 
The architecture of SkySQL
The architecture of SkySQLThe architecture of SkySQL
The architecture of SkySQLMariaDB plc
 

Mehr von MariaDB plc (20)

MariaDB Paris Workshop 2023 - MaxScale 23.02.x
MariaDB Paris Workshop 2023 - MaxScale 23.02.xMariaDB Paris Workshop 2023 - MaxScale 23.02.x
MariaDB Paris Workshop 2023 - MaxScale 23.02.x
 
MariaDB Paris Workshop 2023 - Newpharma
MariaDB Paris Workshop 2023 - NewpharmaMariaDB Paris Workshop 2023 - Newpharma
MariaDB Paris Workshop 2023 - Newpharma
 
MariaDB Paris Workshop 2023 - Cloud
MariaDB Paris Workshop 2023 - CloudMariaDB Paris Workshop 2023 - Cloud
MariaDB Paris Workshop 2023 - Cloud
 
MariaDB Paris Workshop 2023 - MariaDB Enterprise
MariaDB Paris Workshop 2023 - MariaDB EnterpriseMariaDB Paris Workshop 2023 - MariaDB Enterprise
MariaDB Paris Workshop 2023 - MariaDB Enterprise
 
MariaDB Paris Workshop 2023 - Performance Optimization
MariaDB Paris Workshop 2023 - Performance OptimizationMariaDB Paris Workshop 2023 - Performance Optimization
MariaDB Paris Workshop 2023 - Performance Optimization
 
MariaDB Paris Workshop 2023 - MaxScale
MariaDB Paris Workshop 2023 - MaxScale MariaDB Paris Workshop 2023 - MaxScale
MariaDB Paris Workshop 2023 - MaxScale
 
MariaDB Paris Workshop 2023 - novadys presentation
MariaDB Paris Workshop 2023 - novadys presentationMariaDB Paris Workshop 2023 - novadys presentation
MariaDB Paris Workshop 2023 - novadys presentation
 
MariaDB Paris Workshop 2023 - DARVA presentation
MariaDB Paris Workshop 2023 - DARVA presentationMariaDB Paris Workshop 2023 - DARVA presentation
MariaDB Paris Workshop 2023 - DARVA presentation
 
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server
MariaDB Tech und Business Update Hamburg 2023 - MariaDB Enterprise Server
 
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-Backup
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-BackupMariaDB SkySQL Autonome Skalierung, Observability, Cloud-Backup
MariaDB SkySQL Autonome Skalierung, Observability, Cloud-Backup
 
Einführung : MariaDB Tech und Business Update Hamburg 2023
Einführung : MariaDB Tech und Business Update Hamburg 2023Einführung : MariaDB Tech und Business Update Hamburg 2023
Einführung : MariaDB Tech und Business Update Hamburg 2023
 
Hochverfügbarkeitslösungen mit MariaDB
Hochverfügbarkeitslösungen mit MariaDBHochverfügbarkeitslösungen mit MariaDB
Hochverfügbarkeitslösungen mit MariaDB
 
Die Neuheiten in MariaDB Enterprise Server
Die Neuheiten in MariaDB Enterprise ServerDie Neuheiten in MariaDB Enterprise Server
Die Neuheiten in MariaDB Enterprise Server
 
Global Data Replication with Galera for Ansell Guardian®
Global Data Replication with Galera for Ansell Guardian®Global Data Replication with Galera for Ansell Guardian®
Global Data Replication with Galera for Ansell Guardian®
 
Introducing workload analysis
Introducing workload analysisIntroducing workload analysis
Introducing workload analysis
 
Under the hood: SkySQL monitoring
Under the hood: SkySQL monitoringUnder the hood: SkySQL monitoring
Under the hood: SkySQL monitoring
 
Introducing the R2DBC async Java connector
Introducing the R2DBC async Java connectorIntroducing the R2DBC async Java connector
Introducing the R2DBC async Java connector
 
MariaDB Enterprise Tools introduction
MariaDB Enterprise Tools introductionMariaDB Enterprise Tools introduction
MariaDB Enterprise Tools introduction
 
Faster, better, stronger: The new InnoDB
Faster, better, stronger: The new InnoDBFaster, better, stronger: The new InnoDB
Faster, better, stronger: The new InnoDB
 
The architecture of SkySQL
The architecture of SkySQLThe architecture of SkySQL
The architecture of SkySQL
 

Kürzlich hochgeladen

Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 

Kürzlich hochgeladen (20)

Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 

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!

Hinweis der Redaktion

  1. Note that DB in MariaDB is not bolded