Commonly Used Queries

This guide provides examples of frequent SQL patterns, such as finding maximum values, calculating averages, and using auto-increment columns.

This page is intended to be a quick reference of commonly-used and/or useful queries in MariaDB.

Cover

WEBINAR

MariaDB 101: Learning the Basics of MariaDB

Creating a Table

CREATE TABLE t1 ( a INT );
CREATE TABLE t2 ( b INT );
CREATE TABLE student_tests (
 name CHAR(10), test CHAR(10), 
 score TINYINT, test_date DATE
);

See CREATE TABLE for more.

Inserting Records

INSERT INTO t1 VALUES (1), (2), (3);
INSERT INTO t2 VALUES (2), (4);

INSERT INTO student_tests 
 (name, test, score, test_date) VALUES
 ('Chun', 'SQL', 75, '2012-11-05'), 
 ('Chun', 'Tuning', 73, '2013-06-14'),
 ('Esben', 'SQL', 43, '2014-02-11'), 
 ('Esben', 'Tuning', 31, '2014-02-09'), 
 ('Kaolin', 'SQL', 56, '2014-01-01'),
 ('Kaolin', 'Tuning', 88, '2013-12-29'), 
 ('Tatiana', 'SQL', 87, '2012-04-28'), 
 ('Tatiana', 'Tuning', 83, '2013-09-30');

See INSERT for more.

Using AUTO_INCREMENT

The AUTO_INCREMENT attribute is used to automatically generate a unique identity for new rows.

When inserting, the id field can be omitted, and is automatically created.

See AUTO_INCREMENT for more.

Querying from two tables on a common value

This kind of query is called a join - see JOINS for more.

Finding the Maximum Value

See the MAX() function for more, as well as Finding the maximum value and grouping the results below for a more practical example.

Finding the Minimum Value

See the MIN() function for more.

Finding the Average Value

See the AVG() function for more.

Finding the Maximum Value and Grouping the Results

See the MAX() function for more.

Ordering Results

See ORDER BY for more.

Finding the Row with the Minimum of a Particular Column

In this example, we want to find the lowest test score for any student.

Finding Rows with the Maximum Value of a Column by Group

This example returns the best test results of each student:

Calculating Age

The TIMESTAMPDIFF function can be used to calculate someone's age:

See TIMESTAMPDIFF() for more.

Using User-defined Variables

This example sets a user-defined variable with the average test score, and then uses it in a later query to return all results above the average.

User-defined variables can also be used to add an incremental counter to a resultset:

See User-defined Variables for more.

View Tables in Order of Size

Returns a list of all tables in the database, ordered by size:

Removing Duplicates

This example assumes there's a unique ID, but that all other fields are identical. In the example below, there are 4 records, 3 of which are duplicates, so two of the three duplicates need to be removed. The intermediate SELECT is not necessary, but demonstrates what is being returned.

CC BY-SA / Gnu FDL

Last updated

Was this helpful?