Skip to main content
Quick Reference

MariaDB Cheatsheet

MariaDB on one page — tables, AUTO_INCREMENT, LIMIT, joins, indexes, transactions, and the traps that differ from MySQL.

10 sections 10 tables 14 code snippets

Connect

mariadb client

mariadb -u app -p shop

Pick the database

USE shop;
SHOW TABLES;

The names

NameMeaning
mariadbThe client. A mysql command on the same machine is often the same program
-pPrompts for the password. Do not glue the password to the flag
Port 3306The default
USE shopSelects the database for the next statements
SemicolonSends the statement
EngineInnoDB is the default. It has transactions and foreign keys. Aria does not replace it for app tables

This page is MariaDB SQL. A lot of it matches MySQL. The rows below mark the places that do not.

Create a table

Auto-increment and Unicode text

CREATE TABLE books (
  id int PRIMARY KEY AUTO_INCREMENT,
  title varchar(200) NOT NULL,
  pages int NOT NULL,
  price decimal(8, 2) NOT NULL,
  published date NULL,
  CONSTRAINT pages_chk CHECK (pages > 0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Column rules

PieceEffect
AUTO_INCREMENTOne per table, and it must be a key. On InnoDB it is the first column of that key
SERIALShorthand for bigint unsigned not null auto_increment unique
varchar(200)200 characters. INT(11) does not limit the number you can store
utf8mb4Full Unicode, including emoji. The charset name utf8 is the 3-byte charset
Default collationFrom 11.6 the server default is utf8mb4_uca1400_ai_ci. Older servers, and some packages, still use latin1
CHECKEnforced. A false check rejects the row. A NULL check is allowed

Insert

Several rows, and the new ids

INSERT INTO books (title, pages, price)
VALUES
  ('Dune', 412, 18.50),
  ('Neuromancer', 271, 14.00)
RETURNING id;

What comes back

FormResult
RETURNING idEvery new id from this statement. Needs MariaDB 10.5 or newer. MySQL 8.0 has no RETURNING
LAST_INSERT_ID()The first auto value this session just generated, not the highest id in the table
Omitted id, or NULLThe next auto value. 0 does the same unless NO_AUTO_VALUE_ON_ZERO is on
CREATE SEQUENCEA sequence object. MySQL has no CREATE SEQUENCE. Use NEXT VALUE FOR book_seq
Column listName the columns. A later new column will not shift your values
Empty stringA real value. It is not NULL

Select

Ten rows after the sort

SELECT title, pages
FROM books
WHERE pages >= 300
ORDER BY pages DESC
LIMIT 10;

A later page

SELECT title, pages
FROM books
ORDER BY id
LIMIT 10 OFFSET 20;

Read rules

FormMeaning
LIMIT 10Stops after 10 rows. Without ORDER BY those 10 are not defined
LIMIT 10 OFFSET 20Skips 20, then returns 10. LIMIT 20, 10 is the other way around: offset first
IS NULLThe null test. = NULL is never true
COUNT(*)Counts rows. COUNT(title) skips NULL
Default collationCase-insensitive. Dune and dune compare equal under utf8mb4_uca1400_ai_ci
utf8mb4_binA binary collation. Comparisons become case-sensitive

Update & delete

Change a price

UPDATE books
SET price = 19
WHERE title = 'Dune';

Remove the short ones

DELETE FROM books
WHERE pages < 100;

Write rules

StatementTouches
UPDATE ... SETThe named columns on rows that pass WHERE. A successful statement commits
DELETE FROMWhole rows that pass WHERE. The table stays
No WHEREEvery row. The client will not ask you to confirm
TRUNCATE TABLE booksEmpties the table and implies a commit. It also resets AUTO_INCREMENT
CREATE or ALTERAlso commits an open transaction before the DDL runs
Inside BEGINA plain UPDATE waits. DDL will not wait with it

Joins

Orders with their book

SELECT o.id, b.title, o.amount
FROM orders AS o
INNER JOIN books AS b ON b.id = o.book_id;

SELECT o.id, b.title
FROM orders AS o
LEFT JOIN books AS b ON b.id = o.book_id;

Which rows survive

JoinKeeps
INNER JOINOnly rows that match on both sides
LEFT JOINEvery left row. Missing right-side columns are NULL
ONThe match. A right-table filter in WHERE turns a left join into an inner join
AS oA short name. Required once both tables have id
WHERE b.id IS NULLLeft rows whose book is missing
ON DELETE RESTRICTThe usual default. A parent delete fails while a child row points at it

Group & count

Revenue per book

SELECT b.id, b.title,
       COUNT(*) AS sold,
       SUM(o.amount) AS revenue
FROM orders AS o
INNER JOIN books AS b ON b.id = o.book_id
GROUP BY b.id, b.title
HAVING SUM(o.amount) > 100
ORDER BY revenue DESC;

Aggregate rules

FormMeaning
COUNT(*)Rows in the group, including rows with NULL
SUM / AVGSkip NULL. AVG of no rows is NULL, not zero
ONLY_FULL_GROUP_BYRequires every selected plain column to be grouped or aggregated. MySQL 8 turns it on. Check sql_mode on MariaDB
GROUP BYDoes not promise a sort. Add ORDER BY
HAVINGFilters groups. WHERE cannot see SUM
DISTINCTOne copy of each selected row. It is not a substitute for GROUP BY when you need SUM

Indexes & foreign keys

Index the column you look up

CREATE INDEX idx_books_title ON books (title);

ALTER TABLE orders
  ADD CONSTRAINT fk_orders_book
  FOREIGN KEY (book_id) REFERENCES books (id);

What InnoDB stores

KeyDetail
Primary keyClustered. The table is stored in that order. A missing primary key makes InnoDB pick one
(title, pages)Serves title, and title plus pages. Not pages alone
UNIQUERejects a second equal value. Several NULLs are allowed
Foreign keyInnoDB adds an index on book_id when you did not create one
EXPLAINtype: ALL is a full table scan
JSONStored as LONGTEXT with a check, using utf8mb4_bin. MySQL stores a binary JSON value

Transactions

Two writes, one outcome

BEGIN;
UPDATE books SET price = price - 1 WHERE id = 1;
INSERT INTO orders (book_id, amount) VALUES (1, 17.50);
COMMIT;

When the work sticks

FactWhy it matters
AutocommitOn. One statement outside a transaction commits when it succeeds
BEGINHolds the following DML until COMMIT or ROLLBACK
DDLCREATE, ALTER, and DROP commit the open transaction first
TRUNCATEImplies a commit. Use DELETE when you still need to roll back
Auto value and rollbackThe consumed AUTO_INCREMENT value is not reused
Aria and MyISAMIgnore transactions and foreign keys. Keep app tables on InnoDB

Interview traps

Traps worth memorising

TrapWhat happensPrefer
Copying MySQL 8 defaultsCharset and collation can differ, including latin1 on older serversutf8mb4 on the database, with the collation named
Charset name utf8Three bytes per character. Emoji is rejected or truncatedutf8mb4
A JSON column like MySQLMariaDB stores LONGTEXT plus a check. Indexes and extraction cost differTest the JSON path your app uses
LIMIT 20, 10Offset 20, then 10 rowsLIMIT 10 OFFSET 20
WHERE title = NULLNever matchesIS NULL
An empty titleA stored value. IS NULL does not find itIS NULL only when you mean NULL
Inserting 0 into AUTO_INCREMENTA new id, unless NO_AUTO_VALUE_ON_ZERO is onOmit the column
LAST_INSERT_ID() after several rowsThe first generated id of that statementRETURNING when you need every id
Expecting a gapless idA rollback, a delete, or a failed insert skips numbersA key that may have gaps
UNIQUE and two NULLsBoth are allowedA NOT NULL column when one missing value is the limit
CREATE TABLE after an UPDATE in a transactionThe update is already committedFinish the DML, then run DDL
Dune and dune under the default collationThey compare equalA binary collation when case matters

The page

ORDER BY id
LIMIT 10 OFFSET 20

The new ids

RETURNING id

How to use this page: connect with mariadb, create books as InnoDB with utf8mb4, and insert one title with RETURNING id. Then SELECT with ORDER BY and LIMIT, and wrap two writes in BEGIN before you COMMIT.