brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: mariadb -B -N -e prints query results as bare tab-separated rows for scripts

Mariadb
~/tips/tip-database-mariadb-batch-skip-column-names

mariadb -B -N -e "SELECT id, email FROM users WHERE active" appdb

Runs one query and prints plain tab-separated rows without borders or a header line.

The pretty ASCII table of the MariaDB client is great for reading and annoying for a shell script. If you want to loop over the result of a query, you need the rows without borders and without the header line.

mariadb -B -N -e "SELECT id, email FROM users WHERE active" appdb

The docs describe the pieces. -e (--execute) runs the statement and quits. -B (--batch) prints results with a tab as the column separator and each row on a new line. -N (--skip-column-names) leaves out the column names. The result is one line per row, which while read, cut or awk handle without trouble:

mariadb -B -N -e "SELECT id, email FROM users WHERE active" appdb | cut -f2

Two details are worth knowing. The docs say that batch mode gives nontabular output and escapes special characters, so a tab or newline inside a value shows up as an escape sequence. If you want the raw text, they mention the --raw option. And -e on its own already produces output in the batch format. The docs say the default output format with -e is like that produced with --batch, so for the table format back you add -t (--table).

With -B the client also does not use its history file, so these one-liners do not end up in your history.

The caveat is that tab-separated text gets awkward when values themselves contain tabs or newlines, and that is exactly the case where the escaping above matters. For anything more than a quick loop, I would select only the one column I need.

Further reading: MariaDB documentation: mariadb command-line client

More Mariadb tips ALTER TABLE t ADD COLUMN z INT INVISIBLE; CREATE SEQUENCE s START WITH 100 INCREMENT BY 10; CREATE OR REPLACE TABLE scratch ( mariadb --init-command="SET SESSION sql_mode='STRICT_ALL_TABLES'" mydb mariadb-admin -u root -p extended-status --relative --sleep=10 \ All Mariadb tips (15) All topics

Link