Data Types & MySQL-specific SQL
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page covers what is particular to MySQL: its column types and their pitfalls, character sets, the
statements that exist only in MySQL (INSERT ... ON DUPLICATE KEY UPDATE, REPLACE, multi-table UPDATE), the
sql_mode setting that decides whether MySQL is strict or forgiving, and the catalog and SHOW commands. Standard
SQL is not repeated here: for joins, subqueries, set operations and the standard window-function semantics see
Querying Data, Modifying Data,
DDL and
Aggregate & Window Functions.
All outputs were produced on MySQL 26.10.0 with the default sql_mode, against the shop database from
Getting Started and a scratch database called lab.
Numeric types
| Type | Storage | Range or notes |
|---|---|---|
|
1, 2, 3, 4, 8 bytes |
Signed or |
|
Variable |
Exact fixed-point, up to 65 digits; use for money |
|
4, 8 bytes |
Approximate IEEE-754 binary floating point |
|
— |
|
The number in INT(11) is only a legacy display width and does not change the range; the display width is
deprecated and not used by modern clients.
Out of range values. With the default strict sql_mode MySQL rejects a value that does not fit; in a lax mode it
silently clamps it and raises a warning:
CREATE TABLE lab.t_int (a tinyint, b tinyint unsigned, c int);
INSERT INTO lab.t_int VALUES (127, 255, 2147483647);
INSERT INTO lab.t_int VALUES (128, 1, 1);
SET SESSION sql_mode = '';
INSERT INTO lab.t_int VALUES (128, 1, 1);
SHOW WARNINGS;
SELECT * FROM lab.t_int;
ERROR 1264 (22003): Out of range value for column 'a' at row 1
+---------+------+--------------------------------------------+
| Level | Code | Message |
+---------+------+--------------------------------------------+
| Warning | 1264 | Out of range value for column 'a' at row 1 |
+---------+------+--------------------------------------------+
+------+------+------------+
| a | b | c |
+------+------+------------+
| 127 | 255 | 2147483647 |
| 127 | 1 | 1 |
+------+------+------------+
The second row holds 127, not the 128 that was inserted. This is the strongest reason to keep strict mode on.
Exact versus approximate. DECIMAL arithmetic is exact; FLOAT and DOUBLE are not, and a decimal literal
does not equal its float representation:
SELECT 0.1+0.2 AS dec_sum, 0.1e0+0.2e0 AS float_sum, 0.1+0.2=0.3 AS dec_eq,
CAST(0.1 AS DOUBLE)+CAST(0.2 AS DOUBLE)=0.3 AS dbl_eq;
CREATE TABLE lab.t_dec (price decimal(5,2), f float, d double);
INSERT INTO lab.t_dec VALUES (999.99, 0.1, 0.1);
INSERT INTO lab.t_dec VALUES (1000.00, 0.1, 0.1);
SELECT price, f=0.1 AS f_eq, d=0.1 AS d_eq FROM lab.t_dec;
SELECT 5/2, 5 DIV 2, 5 % 2, -5 DIV 2;
+---------+---------------------+--------+--------+
| dec_sum | float_sum | dec_eq | dbl_eq |
+---------+---------------------+--------+--------+
| 0.3 | 0.30000000000000004 | 1 | 0 |
+---------+---------------------+--------+--------+
ERROR 1264 (22003): Out of range value for column 'price' at row 1
+--------+------+------+
| price | f_eq | d_eq |
+--------+------+------+
| 999.99 | 0 | 1 |
+--------+------+------+
+--------+---------+-------+----------+
| 5/2 | 5 DIV 2 | 5 % 2 | -5 DIV 2 |
+--------+---------+-------+----------+
| 2.5000 | 2 | 1 | -2 |
+--------+---------+-------+----------+
(The failing INSERT is the 1000.00 into DECIMAL(5,2), whose limit is 999.99. / always yields a decimal;
DIV is integer division and truncates toward zero.)
Strings and character sets
String columns are CHAR(n), VARCHAR(n) (n counts characters, not bytes), the TINYTEXT .. LONGTEXT family,
and the binary counterparts BINARY, VARBINARY and BLOB. Every string column has a character set (the
encoding) and a collation (the comparison and sort rules).
-
Use
utf8mb4. It is the real UTF-8 (up to 4 bytes per character, including emoji) and the server default.utf8is an alias for the olderutf8mb3, which stores at most 3 bytes per character and cannot hold characters outside the Basic Multilingual Plane; the name is deprecated. -
The default collation is
utf8mb4_0900_ai_ci: based on Unicode 9.0 (0900), *a*ccent-*i*nsensitive, *c*ase-*i*nsensitive.utf8mb4_bincompares bytes;utf8mb4_unicode_ciandutf8mb4_general_ciare older case-insensitive collations.
SELECT @@character_set_server, @@collation_server;
SELECT 'a' = 'A' AS ci, 'a' = 'á' AS ai, 'a' COLLATE utf8mb4_0900_as_cs = 'A' AS cs;
SELECT LENGTH('é€😀') AS bytes, CHAR_LENGTH('é€😀') AS chars;
+------------------------+--------------------+
| @@character_set_server | @@collation_server |
+------------------------+--------------------+
| utf8mb4 | utf8mb4_0900_ai_ci |
+------------------------+--------------------+
+----+----+------+
| ci | ai | cs |
+----+----+------+
| 1 | 1 | 0 |
+----+----+------+
+-------+-------+
| bytes | chars |
+-------+-------+
| 9 | 3 |
+-------+-------+
Because the default collation is case-insensitive, a UNIQUE index treats Ada and ADA as the same value, and
WHERE v = 'ada' finds both:
CREATE TABLE lab.t_ci (id int auto_increment primary key, v varchar(20) unique);
INSERT INTO lab.t_ci(v) VALUES ('Ada');
INSERT INTO lab.t_ci(v) VALUES ('ADA');
SELECT * FROM lab.t_ci WHERE v = 'ada';
ERROR 1062 (23000): Duplicate entry 'ADA' for key 't_ci.v'
+----+------+
| id | v |
+----+------+
| 1 | Ada |
+----+------+
Declare a column COLLATE utf8mb4_0900_as_cs or utf8mb4_bin when you need case-sensitive matching. The
character set of the client connection matters too: the mysql client in the Docker image defaults to
latin1, so pass --default-character-set=utf8mb4 (see Getting Started).
ENUM and SET
ENUM stores one value out of a fixed list in 1 or 2 bytes; SET stores any combination of up to 64 listed
members in a bit field. Both are accepted and shown as strings but stored, and sorted, by position.
CREATE TABLE lab.t_enum (
id int auto_increment primary key,
status enum('open','shipped','cancelled') NOT NULL,
flags set('gift','fragile','express'));
INSERT INTO lab.t_enum(status, flags) VALUES ('shipped','gift,express'), ('open','');
INSERT INTO lab.t_enum(status) VALUES ('lost');
SELECT id, status, status+0 AS idx, flags, flags+0 AS bits, FIND_IN_SET('gift', flags) AS has_gift
FROM lab.t_enum ORDER BY status;
ERROR 1265 (01000): Data truncated for column 'status' at row 1
+----+---------+-----+--------------+------+----------+
| id | status | idx | flags | bits | has_gift |
+----+---------+-----+--------------+------+----------+
| 2 | open | 1 | | 0 | 0 |
| 1 | shipped | 2 | gift,express | 5 | 1 |
+----+---------+-----+--------------+------+----------+
An invalid value is an error in strict mode. The pitfalls: adding a member in the middle of the list renumbers
the existing ones, changing the sort order and (for a non-trailing change) forcing a table rebuild, and the
list cannot be queried like a table. A CHECK constraint (as the shop uses for status) or a lookup table with
a foreign key is usually more flexible.
Date and time types
| Type | Notes |
|---|---|
|
Calendar date; time of day or duration |
|
|
|
|
|
4-digit year |
fsp is the fractional-seconds precision, 0..6. The difference between DATETIME and TIMESTAMP is visible
as soon as the session time zone changes:
CREATE TABLE lab.t_time (id int auto_increment primary key, dt datetime(3), ts timestamp(3) NULL DEFAULT NULL);
SET time_zone = '+00:00';
INSERT INTO lab.t_time(dt, ts) VALUES ('2026-06-01 12:00:00.123', '2026-06-01 12:00:00.123');
SELECT dt, ts FROM lab.t_time;
SET time_zone = 'Europe/Madrid';
SELECT dt, ts FROM lab.t_time;
+-------------------------+-------------------------+
| dt | ts |
+-------------------------+-------------------------+
| 2026-06-01 12:00:00.123 | 2026-06-01 12:00:00.123 |
+-------------------------+-------------------------+
+-------------------------+-------------------------+
| dt | ts |
+-------------------------+-------------------------+
| 2026-06-01 12:00:00.123 | 2026-06-01 14:00:00.123 |
+-------------------------+-------------------------+
The DATETIME is unchanged while the TIMESTAMP moved two hours (Madrid is UTC+2 in June). Time-zone rules:
-
@@time_zoneisSYSTEMby default (the operating system’s zone). Set it per session with an offset ('+00:00') or, when the time-zone tables are loaded, a name ('Europe/Madrid'). The named form worked here because the Docker image populates them; on a hand-built server load them withmysql_tzinfo_to_sql. -
The cleanest design is to store instants as
TIMESTAMPor as UTCDATETIMEand convert in the application;CONVERT_TZ()converts between zones inside a query. -
TIMESTAMPhas the year-2038 limit, and a value beyond it is rejected:
SET time_zone = '+00:00';
INSERT INTO lab.t_time(dt, ts) VALUES ('2040-01-01 00:00:00', '2040-01-01 00:00:00');
SELECT CONVERT_TZ('2026-06-01 12:00:00','UTC','Europe/Madrid') AS named_zone,
FROM_UNIXTIME(2147483647) AS last_second;
ERROR 1292 (22007): Incorrect datetime value: '2040-01-01 00:00:00' for column 'ts' at row 1
+---------------------+---------------------+
| named_zone | last_second |
+---------------------+---------------------+
| 2026-06-01 14:00:00 | 2038-01-19 03:14:07 |
+---------------------+---------------------+
(Both columns were in the failing row, and the message names ts; the row is rejected as a whole.) Invalid
dates are also rejected in strict mode: '2026-02-30 00:00:00' and '0000-00-00' both fail with error 1292,
because the default mode includes NO_ZERO_DATE and NO_ZERO_IN_DATE.
AUTO_INCREMENT
An AUTO_INCREMENT column generates the next integer for each new row. It must be the first column of an index
(normally the primary key).
CREATE TABLE lab.t_ai (id int auto_increment primary key, v varchar(10) unique);
INSERT INTO lab.t_ai(v) VALUES ('a'),('b'),('c');
INSERT INTO lab.t_ai(v) VALUES ('a');
INSERT INTO lab.t_ai(v) VALUES ('d');
SELECT LAST_INSERT_ID();
SELECT * FROM lab.t_ai;
ERROR 1062 (23000): Duplicate entry 'a' for key 't_ai.v'
+------------------+
| LAST_INSERT_ID() |
+------------------+
| 5 |
+------------------+
+----+------+
| id | v |
+----+------+
| 1 | a |
| 2 | b |
| 3 | c |
| 5 | d |
+----+------+
Id 4 is missing: the failed duplicate insert consumed it. Gaps are normal; never rely on a contiguous sequence.
The counter also does not go backwards after a DELETE. Continuing the example, three more rows get 6, 7 and 8;
after they and row 5 are deleted, the next insert is still given 9:
INSERT INTO lab.t_ai(v) VALUES ('e'),('f'),('g');
DELETE FROM lab.t_ai WHERE id >= 5;
INSERT INTO lab.t_ai(v) VALUES ('h');
SELECT * FROM lab.t_ai;
+----+------+
| id | v |
+----+------+
| 1 | a |
| 2 | b |
| 3 | c |
| 9 | h |
+----+------+
Other points:
-
LAST_INSERT_ID()is per connection, so concurrent sessions do not see each other’s ids; after a multi-rowINSERTit returns the id of the first row inserted. -
A rolled-back insert also keeps its id. With
innodb_autoinc_lock_mode = 2(the default here, "interleaved") ids from concurrent multi-row inserts may interleave, which is fine for uniqueness but not for assuming adjacent ids. -
The next value is kept in memory and persisted, so it survives restarts.
-
auto_increment_incrementandauto_increment_offset(both 1 here) let several sources generate non-overlapping ids. -
The
AUTO_INCREMENTcolumn ininformation_schema.tablesis cached statistics: it readsinformation_schema_stats_expiryseconds old (86400 here). RunANALYZE TABLEorSET SESSION information_schema_stats_expiry = 0for fresh values.
The choice between auto-increment keys and UUIDs is measured on Indexing.
Generated columns
A generated column is computed from other columns of the same row, either VIRTUAL (computed on read, the
default, no storage) or STORED (computed on write). They can be indexed, which makes them the way to index an
expression:
CREATE TABLE lab.t_gen (
id int auto_increment primary key,
price decimal(10,2), qty int,
total decimal(12,2) AS (price*qty) STORED,
email varchar(100),
domain varchar(100) AS (SUBSTRING_INDEX(email,'@',-1)) VIRTUAL,
KEY(domain));
INSERT INTO lab.t_gen(price, qty, email) VALUES (10.50, 3, 'ada@example.com'), (2, 5, 'bob@test.org');
INSERT INTO lab.t_gen(price, qty, total) VALUES (1,1,5);
SELECT * FROM lab.t_gen;
ERROR 3105 (HY000): The value specified for generated column 'total' in table 't_gen' is not allowed.
+----+-------+------+-------+-----------------+-------------+
| id | price | qty | total | email | domain |
+----+-------+------+-------+-----------------+-------------+
| 1 | 10.50 | 3 | 31.50 | ada@example.com | example.com |
| 2 | 2.00 | 5 | 10.00 | bob@test.org | test.org |
+----+-------+------+-------+-----------------+-------------+
You cannot write a generated column. A query that filters on domain uses the index on it (the plan shows
Index lookup on t_gen using domain). A functional index on an expression, covered on
Indexing, achieves the same without a visible column.
INSERT … ON DUPLICATE KEY UPDATE, INSERT IGNORE and REPLACE
These statements resolve a conflict on a PRIMARY KEY or UNIQUE index. The three statements react to a key conflict differently:
Starting state:
CREATE TABLE lab.kv (k varchar(10) PRIMARY KEY, v int NOT NULL DEFAULT 0, note varchar(20), hits int NOT NULL DEFAULT 1);
INSERT INTO lab.kv(k, v) VALUES ('a', 1), ('b', 2);
ON DUPLICATE KEY UPDATE is MySQL’s upsert. Reference the would-be-inserted values through a row alias
(AS new); the older VALUES(col) function is deprecated.
INSERT INTO lab.kv(k, v) VALUES ('a', 10) ON DUPLICATE KEY UPDATE v = v + VALUES(v);
SELECT ROW_COUNT();
INSERT INTO lab.kv(k, v) VALUES ('a', 10) AS new ON DUPLICATE KEY UPDATE v = kv.v + new.v, hits = hits + 1;
SELECT ROW_COUNT();
INSERT INTO lab.kv(k, v) VALUES ('a', 10) AS new ON DUPLICATE KEY UPDATE v = v;
INSERT INTO lab.kv(k, v) VALUES ('z', 26) AS new ON DUPLICATE KEY UPDATE v = kv.v + new.v;
SELECT ROW_COUNT();
SELECT * FROM lab.kv;
+-------------+
| ROW_COUNT() |
+-------------+
| 2 |
+-------------+
+-------------+
| ROW_COUNT() |
+-------------+
| 2 |
+-------------+
ERROR 1052 (23000): Column 'v' in field list is ambiguous
+-------------+
| ROW_COUNT() |
+-------------+
| 1 |
+-------------+
+---+----+------+------+
| k | v | note | hits |
+---+----+------+------+
| a | 21 | NULL | 2 |
| b | 2 | NULL | 1 |
| z | 26 | NULL | 1 |
+---+----+------+------+
ROW_COUNT() is 1 for an insert, 2 for a row updated by the conflict clause (and 0 if the update changed
nothing). With a row alias, name the table’s column explicitly (kv.v); an unqualified v is ambiguous, as the
third statement shows. Row a ended at 1 + 10 + 10 = 21.
INSERT IGNORE turns most errors into warnings and skips the offending row; it also silently converts bad
values, so use it sparingly.
INSERT IGNORE INTO lab.kv(k, v) VALUES ('a', 99), ('c', 3);
SHOW WARNINGS;
INSERT IGNORE INTO lab.kv(k, v) VALUES ('d', NULL);
SHOW WARNINGS;
+---------+------+------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------+
| Warning | 1062 | Duplicate entry 'a' for key 'kv.PRIMARY' |
+---------+------+------------------------------------------+
+---------+------+---------------------------+
| Level | Code | Message |
+---------+------+---------------------------+
| Warning | 1048 | Column 'v' cannot be null |
+---------+------+---------------------------+
Row c was inserted, row a kept its value, and d was inserted with v = 0, a NULL quietly replaced by
the column’s implicit default.
REPLACE deletes the conflicting row and inserts the new one, so it resets columns you did not list and fires
delete triggers and foreign-key actions:
REPLACE INTO lab.kv(k, v) VALUES ('a', 5);
SELECT ROW_COUNT();
SELECT * FROM lab.kv ORDER BY k;
+-------------+
| ROW_COUNT() |
+-------------+
| 2 |
+-------------+
+---+----+------+------+
| k | v | note | hits |
+---+----+------+------+
| a | 5 | NULL | 1 |
| b | 2 | NULL | 1 |
| c | 3 | NULL | 1 |
| d | 0 | NULL | 1 |
| z | 26 | NULL | 1 |
+---+----+------+------+
hits went back from 2 to 1: the row was deleted and re-created. Prefer ON DUPLICATE KEY UPDATE unless you
really mean "replace the whole row".
LIMIT and multi-table UPDATE / DELETE
LIMIT count [OFFSET n] is how MySQL pages and caps results; for the cost of large offsets and keyset
alternatives see Pagination Strategies. MySQL also accepts ORDER BY
and LIMIT on single-table UPDATE and DELETE, and joins in the statement itself:
CREATE TEMPORARY TABLE p2 AS SELECT * FROM shop.products;
UPDATE p2 JOIN shop.order_items i ON i.sku = p2.sku SET p2.stock = p2.stock - i.qty WHERE i.order_id = 1001;
SELECT sku, stock FROM p2 WHERE sku IN ('A-1','B-7');
UPDATE p2 SET stock = stock + 1 ORDER BY sku LIMIT 2;
DELETE p2 FROM p2 JOIN shop.order_items i ON i.sku = p2.sku WHERE i.order_id = 1005;
SELECT sku FROM p2 ORDER BY sku;
DELETE FROM p2 ORDER BY stock DESC LIMIT 1;
SELECT COUNT(*) AS remaining FROM p2;
+-----+-------+
| sku | stock |
+-----+-------+
| A-1 | 11 |
| B-7 | 148 |
+-----+-------+
+-----+
| sku |
+-----+
| A-1 |
| A-2 |
| B-7 |
| C-3 |
+-----+
+-----------+
| remaining |
+-----------+
| 3 |
+-----------+
Order 1001 holds one A-1 and two B-7. DELETE p2 FROM p2 JOIN ... names the table whose rows are deleted
before FROM; here it removed C-9, the product on order 1005. Always SELECT with the same join first, or
run the statement inside a transaction, before a multi-table DELETE. Row order in ORDER BY ... LIMIT is only
deterministic if the ORDER BY is unique.
Window functions and CTEs
Window functions and common table expressions (including WITH RECURSIVE) have been available since MySQL 8.0,
so they work on every supported release. Semantics are in
Aggregate & Window Functions; one MySQL example over the shop
combines a CTE with a running total and a rank:
WITH order_totals AS (
SELECT o.id, o.customer_id, SUM(i.qty*i.price) AS total
FROM orders o JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled' GROUP BY o.id, o.customer_id)
SELECT c.name, t.id, t.total,
SUM(t.total) OVER (PARTITION BY c.id ORDER BY t.id) AS running,
RANK() OVER (ORDER BY t.total DESC) AS rnk
FROM order_totals t JOIN customers c ON c.id = t.customer_id
ORDER BY c.name, t.id;
+----------------+------+---------+---------+-----+
| name | id | total | running | rnk |
+----------------+------+---------+---------+-----+
| Ada Lovelace | 1001 | 398.98 | 398.98 | 2 |
| Ada Lovelace | 1002 | 279.00 | 677.98 | 3 |
| Ada Lovelace | 1007 | 189.50 | 867.48 | 4 |
| Alan Turing | 1003 | 117.00 | 117.00 | 6 |
| Alan Turing | 1008 | 124.95 | 241.95 | 5 |
| Grace Hopper | 1004 | 1456.00 | 1456.00 | 1 |
| Linus Torvalds | 1006 | 63.99 | 63.99 | 7 |
+----------------+------+---------+---------+-----+
A recursive CTE is also the simplest way to generate rows. MySQL limits recursion with
cte_max_recursion_depth (1000 by default), which the bulk-data examples on the Indexing page raise:
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i<5) SELECT i, i*i AS sq FROM n;
+------+------+
| i | sq |
+------+------+
| 1 | 1 |
| 2 | 4 |
| 3 | 9 |
| 4 | 16 |
| 5 | 25 |
+------+------+
sql_mode and strict mode
sql_mode is a comma-separated list of flags that change how forgiving the server is. The default on this
server is:
SELECT @@global.sql_mode;
ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
-
STRICT_TRANS_TABLES— invalid or out-of-range data in a transactional table is an error, not a warning (the clamping seen above only happens when it is off). -
ERROR_FOR_DIVISION_BY_ZERO— division by zero in a data-changing statement is an error. In a plainSELECTit still returnsNULL:SELECT 1/0givesNULLwith only a warning, whatever the mode. -
NO_ZERO_DATE,NO_ZERO_IN_DATE— reject0000-00-00and dates with a zero month or day. -
NO_ENGINE_SUBSTITUTION— error instead of silently using another engine when the requested one is missing. -
ONLY_FULL_GROUP_BY— the next section. -
TRADITIONALis a shortcut that addsSTRICT_ALL_TABLESand friends.
Set it per session (SET SESSION sql_mode = '...'), per server in my.cnf, or at runtime with
SET GLOBAL / SET PERSIST (see Administration). Keep strict mode on for
new applications, and when migrating an old application off a lax mode, fix the data errors rather than
relaxing the mode.
GROUP BY and ONLY_FULL_GROUP_BY
With ONLY_FULL_GROUP_BY, a query that selects a non-aggregated column that is not in the GROUP BY and not
functionally dependent on it is rejected, as in standard SQL. Without it MySQL picks an arbitrary row:
SELECT city, COUNT(*) FROM customers GROUP BY tier;
SET SESSION sql_mode = REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', '');
SELECT city, COUNT(*) FROM customers GROUP BY tier;
SET SESSION sql_mode = DEFAULT;
SELECT tier, ANY_VALUE(city) AS some_city, COUNT(*) AS n FROM customers GROUP BY tier;
SELECT tier, MIN(name) AS first_name, COUNT(*) AS n FROM customers GROUP BY tier ORDER BY tier;
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'shop.customers.city' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
+----------+----------+
| city | COUNT(*) |
+----------+----------+
| London | 1 |
| Wilmslow | 2 |
| New York | 1 |
+----------+----------+
+------------+-----------+---+
| tier | some_city | n |
+------------+-----------+---+
| pro | London | 1 |
| free | Wilmslow | 2 |
| enterprise | New York | 1 |
+------------+-----------+---+
+------------+--------------+---+
| tier | first_name | n |
+------------+--------------+---+
| enterprise | Grace Hopper | 1 |
| free | Alan Turing | 2 |
| pro | Ada Lovelace | 1 |
+------------+--------------+---+
For the free tier the city could be Wilmslow or Helsinki: with the mode off, one of the two comes back, with no
warning. Choose a deterministic aggregate (MIN(name)), put the column in the GROUP BY, or, when every
value in the group is known to be the same, say so with ANY_VALUE(). MySQL accepts a non-grouped column when it
is functionally dependent on a grouped primary key, so GROUP BY c.id allows selecting c.name.
INFORMATION_SCHEMA and SHOW
The data dictionary is exposed as read-only views in information_schema (standard-ish, many MySQL
extensions), with performance_schema and sys for runtime state (see
Administration).
SELECT table_name, engine, table_rows, row_format FROM information_schema.tables
WHERE table_schema = 'shop' ORDER BY table_name;
SELECT column_name, data_type, is_nullable, column_key FROM information_schema.columns
WHERE table_schema = 'shop' AND table_name = 'orders';
SELECT constraint_name, table_name, referenced_table_name FROM information_schema.referential_constraints
WHERE constraint_schema = 'shop';
+-------------+--------+------------+------------+
| TABLE_NAME | ENGINE | TABLE_ROWS | ROW_FORMAT |
+-------------+--------+------------+------------+
| customers | InnoDB | 4 | Dynamic |
| order_items | InnoDB | 11 | Dynamic |
| orders | InnoDB | 8 | Dynamic |
| products | InnoDB | 5 | Dynamic |
+-------------+--------+------------+------------+
+-------------+-----------+-------------+------------+
| COLUMN_NAME | DATA_TYPE | IS_NULLABLE | COLUMN_KEY |
+-------------+-----------+-------------+------------+
| id | int | NO | PRI |
| customer_id | varchar | NO | MUL |
| status | varchar | NO | |
| order_date | datetime | NO | |
+-------------+-----------+-------------+------------+
+--------------------+-------------+-----------------------+
| CONSTRAINT_NAME | TABLE_NAME | REFERENCED_TABLE_NAME |
+--------------------+-------------+-----------------------+
| fk_orders_customer | orders | customers |
| fk_items_order | order_items | orders |
| fk_items_product | order_items | products |
+--------------------+-------------+-----------------------+
TABLE_ROWS is an estimate for InnoDB, and the statistics columns of information_schema.tables are cached (see
the note under AUTO_INCREMENT).
The SHOW statements are MySQL-specific shorthand over the same data:
| Statement | Shows |
|---|---|
|
Schemas and tables |
|
Columns, types, keys, defaults |
|
The full |
|
Indexes with cardinality, visibility and prefix lengths |
|
Configuration and counters (add |
|
Connections and the statement each is running |
|
Diagnostics of the last statement |
|
InnoDB internals including the latest deadlock |
SHOW CREATE TABLE shop.orders;
SHOW INDEX FROM shop.order_items;
Create Table: CREATE TABLE `orders` (
`id` int NOT NULL,
`customer_id` varchar(10) NOT NULL,
`status` varchar(20) NOT NULL,
`order_date` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_orders_customer` (`customer_id`),
CONSTRAINT `fk_orders_customer` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`),
CONSTRAINT `chk_status` CHECK ((`status` in (_utf8mb4'open',_utf8mb4'shipped',_utf8mb4'cancelled')))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Note the index fk_orders_customer: MySQL created it automatically for the foreign key, because InnoDB requires
an index on a foreign-key column. SHOW INDEX FROM order_items lists PRIMARY (two columns, cardinality 8 and
11) and fk_items_product (on sku, cardinality 5); indexing is the next page,
Indexing.
Related
-
SQL Reference — standard SQL, which MySQL implements with the exceptions above.
-
JSON — the
JSONtype and path expressions. -
Evolving the Database Model — changing types and
sql_mode-dependent data safely over time.