Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Use the mysql command-line client to connect to a MySQL server, authenticate, and run SQL. For an interactive session, start with mysql -h HOST -P 3306 -u USER -p DATABASE; for a single statement, add --execute; for a saved script, redirect a .sql file into the client.

The examples below use MySQL 8.4 client syntax and show how to connect safely, inspect data, capture output, automate repeatable queries, and diagnose the errors you are most likely to encounter.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The command-line client in one minute

mysql is the terminal program that opens a session with a MySQL server and sends SQL statements to it. The basic connection command is:

mysql -h HOST -P 3306 -u USER -p DATABASE

Replace the capitalized values with the server address, TCP port, account name, and default database. The -p option has no password after it, so the client asks for the password privately. According to the MySQL 8.4 connection-options documentation, -h chooses the host (default localhost), -P chooses the TCP port (default 3306), and -u chooses the account.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.

After authentication, wait for the mysql> prompt, type SQL, and end each statement with a semicolon:

SELECT id, email
FROM users
LIMIT 20;

For a one-off command that should print results and exit, use:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
mysql -h HOST -u USER -p DATABASE --execute='SELECT id, email FROM users LIMIT 20;'

For a repeatable file, run:

mysql -h HOST -u USER -p DATABASE --batch < query.sql

The official mysql client options reference describes --execute as running the statement and quitting, while --batch emits tab-separated rows, puts each row on its own line, and avoids the history file.

What you need before connecting

A command-line query has two separate parts: the client running on your computer or server, and the MySQL server that stores the database. Before you type a command, collect:

  • The host name or IP address of the MySQL server. Omit -h only when the server is on the local machine and the default local connection is appropriate.
  • The TCP port. MySQL commonly uses 3306; specify another value with -P when the server is configured differently.
  • A MySQL account name and its password.
  • The database you want to use as the session’s default database.
  • Network access to the host and a MySQL account with privileges for the objects you intend to read or change.

The database argument is optional at login. If you leave it out, connect first and select a database later with USE database_name;. A missing default database does not prevent authentication; it only means that statements referring to unqualified tables need a database selected first.

Connect interactively, step by step

  1. Open a terminal. Run the client command with the server details:
mysql -h db.example.net -P 3306 -u reporting -p analytics
  1. Enter the password at the prompt. Nothing is echoed while you type. Do not append the password to -p; the security implications are covered below.
  2. Confirm the prompt. A successful login normally leaves you at mysql>. If you supplied analytics, that database is the default for the session.
  3. Check the session before querying data. These read-only statements show where you connected and which database is active:
SELECT DATABASE();
SELECT VERSION();
SHOW TABLES;
  1. Run a query. SQL can span multiple lines; the client sends it when it reaches a semicolon:
SELECT id, email, created_at
FROM users
WHERE created_at >= '2026-01-01'
ORDER BY created_at DESC
LIMIT 20;
  1. Leave the session. Type exit;, quit;, or press Ctrl-D on a Unix-like terminal.

If you forget the semicolon, the client continues to collect input and displays a continuation prompt. Add the semicolon on a new line to execute the complete statement, or cancel the unfinished input with c.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run a single query with --execute

--execute (short form -e) is useful when a command should perform one statement and terminate without an interactive prompt. Put the SQL in quotes so the shell passes it as one argument:

mysql -h db.example.net -u reporting -p analytics 
  --execute='SELECT COUNT(*) AS orders FROM sales.orders;'

The client prompts for the password, executes the statement, prints the result, and quits. This pattern works well for a quick check, a shell script, or a scheduled task that already has a secure way to provide credentials.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Use shell quoting deliberately. Single quotes preserve characters such as spaces, dollar signs, and semicolons from shell expansion. If your SQL itself contains a single quote, either escape it according to your shell’s rules or place the statement in a file and redirect that file instead. For multiple statements, separate each complete statement with a semicolon and verify that the account is allowed to execute all of them:

mysql -h db.example.net -u reporting -p analytics 
  --execute='SELECT COUNT(*) FROM users; SELECT COUNT(*) FROM orders;'

Keep one-off commands small enough to review. A long command line is harder to audit, easier to mistype, and more likely to expose sensitive text in shell history than a protected SQL file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run a saved .sql file

Save repeatable SQL in a plain-text file such as query.sql:

SELECT id, email
FROM users
WHERE status = 'active'
ORDER BY id;

Feed it to the client with input redirection:

mysql -h db.example.net -u reporting -p analytics < query.sql

The shell opens the file and supplies its contents to mysql as standard input. The client processes the statements in order. A file is easier to review, version, rerun, and hand to another operator than a long interactive paste.

For output intended for another program, add batch mode:

mysql -h db.example.net -u reporting -p analytics --batch < query.sql

In batch mode, rows are tab-separated and each row is printed on a separate line. That predictable layout is suitable for a downstream script, while the absence of the history file reduces the chance that an interactive session will retain the statements. Treat the output as delimited text rather than assuming it is CSV: values containing tabs or newlines need careful handling in whatever consumes the result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can also combine a file with a shell pipeline. This keeps the SQL out of the command’s argument list while still avoiding a permanent file:

printf '%sn' "SELECT id, email FROM users LIMIT 20;" 
  | mysql -h db.example.net -u reporting -p analytics --batch

The password prompt still appears on the terminal, because standard input is occupied by the SQL pipeline. Do not place a password in the pipeline text.

Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Interactive versus scripted queries

Choose the mode based on whether you are exploring or repeating a known operation.

Method Best use Experimentation speed Repeatability Error and output handling Credential considerations
Interactive mysql prompt Inspecting schemas, trying filters, and refining a query Fast feedback; edit and rerun statements immediately Low unless you save the statements separately Human-readable output and immediate errors; results are not automatically captured Password is prompted privately; interactive history behavior depends on how you work
--execute One-off checks and short shell commands Fast for a known statement High for the exact command Easy to redirect or test in a script; shell quoting becomes part of the failure surface Use -p without a value or another protected credential method
--batch with redirected SQL Repeatable reports, data checks, and automation Slower to edit than an interactive prompt High; the SQL file can be reviewed and rerun Tab-separated rows and one row per line; straightforward to pipe to another process Keep credentials outside the SQL file and command text

A practical workflow is to explore interactively, save the final statement to a reviewed file, and run that file in batch mode when the operation becomes repeatable.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Protect the password and other credentials

The MySQL manual states: “Specifying a password on the command line should be considered insecure.” The warning appears in the Account User Names and Passwords documentation. A literal form such as -pMySecret can be exposed through shell history, process listings, copied terminal logs, or scripts.

Use the prompt form instead:

mysql -h db.example.net -u reporting -p analytics

When a non-interactive job cannot stop for a prompt, use an option file or login path as documented by MySQL, with file permissions and secret-management controls appropriate to your operating system. Keep the SQL file separate from credentials. Never commit a password, access token, or private connection string to source control.

Use the least-privileged account that can perform the query. A reporting account should not automatically have permission to alter tables, create users, or drop databases. If a query fails with an authorization error, ask for the specific database, table, column, or operation privilege required instead of switching to an all-powerful account.

Useful read-only query patterns

Once connected to the correct database, these patterns help you orient yourself before writing a larger query:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

List databases and tables

SHOW DATABASES;
SHOW TABLES;

SHOW DATABASES only reveals databases your account is permitted to see. Likewise, SHOW TABLES applies to the currently selected default database.

Inspect a table’s columns

DESCRIBE users;
SHOW CREATE TABLE users;

Use the result to confirm column names and types before adding filters, joins, or ordering. If the table is in another database, qualify it explicitly, for example analytics.users.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Limit a trial query

SELECT id, email
FROM users
ORDER BY id
LIMIT 20;

Select only the columns you need while exploring. A narrow projection and a small limit make it easier to validate the shape of the result before requesting a larger data set.

Count rows without printing them all

SELECT COUNT(*) AS row_count
FROM users;

Counts and other aggregates can answer a question without transferring every matching row to your terminal, although execution cost still depends on the schema, indexes, privileges, server configuration, and data volume.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture and reuse output

Redirect standard output when you need a transcript:

mysql -h db.example.net -u reporting -p analytics 
  --batch < query.sql > result.tsv

Use > to replace an existing file or >> to append. Decide which behavior you want before running a report, especially when the output contains confidential data. Protect the result file with the same care as the database data itself.

For a quick terminal check, leave batch mode off so the client presents a more readable table. For automation, batch mode’s tab-separated rows are easier for a parser than the aligned display used interactively. Design the receiving script to handle empty results, NULL values, tabs, and embedded line breaks rather than treating every line as guaranteed business data.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot connection and query failures

“mysql: command not found”

The client executable is not installed or is not on the shell’s PATH. Install the MySQL client package for your operating system, then open a new terminal or add its binary directory to PATH. Verify with:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
mysql --version

The client and server can be on different machines; you need only a compatible client where you run the command, plus network access to the server.

“Can’t connect to MySQL server”

Check the host and port first. A typo in -h, a server listening on a non-default port, a firewall rule, a stopped server, or a network route can all produce a connection failure. Try the explicit port rather than relying on the default:

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
mysql -h db.example.net -P 3307 -u reporting -p analytics

If localhost behaves differently from an IP address, confirm which local connection method your installation uses and test the address supplied by the server administrator. Do not infer that a successful local connection proves remote access is configured.

“Access denied for user”

The server received the connection but rejected the account, password, host authorization, or requested database access. Re-enter the password at the prompt, verify the exact account and host details, and ask an administrator to confirm the account’s permitted source host and privileges. Avoid putting the password into the command while troubleshooting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“No database selected”

Supply a database name at the end of the command:

mysql -h db.example.net -u reporting -p analytics

Alternatively, connect without one and select it after login:

USE analytics;

Qualifying a table as analytics.users is another way to make the target explicit.

The prompt changes to -> or the query does not run

The client is waiting for the statement terminator. Add ; after the SQL. If you started the wrong statement, enter c to cancel the current input and return to mysql>.

The query is rejected or takes too long

Separate syntax errors from execution constraints. Read the server’s error text, check the table and column names with DESCRIBE, and confirm that the account has the required privilege. For slow or resource-heavy work, inspect the schema and indexes with the database administrator and test a limited, read-only version first. There is no universal runtime or throughput figure: performance varies with the target schema, indexes, privileges, server configuration, and data volume.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Operational checks before running a change

The same client can execute statements that modify data, so treat a command-line session as an administrative interface, not merely a viewer.

  • Confirm the host, port, and database in the command before pressing Enter; a valid account on the wrong server is still a dangerous mistake.
  • Start with a read-only SELECT that identifies the rows you intend to affect.
  • Use a transaction strategy appropriate to the statement and the server’s configuration; do not assume that every operation can be undone after the client exits.
  • Run a small, limited test where possible, then review the result before widening the scope.
  • Save the exact SQL file and record the execution context when a query is part of an operational process.
  • Keep exported output and logs out of locations where unrelated users or services can read them.

Reusable command templates

Interactive connection to a local database

mysql -u app_user -p app_db

This relies on the default local host and port. Add -h and -P whenever the server is remote or uses a non-default port.

One-off result for a shell check

mysql -h db.example.net -u reporting -p analytics 
  --execute='SELECT COUNT(*) AS active_users FROM users WHERE status = "active";'

Use shell quoting that preserves the SQL exactly. The example uses double quotes inside a single-quoted shell argument; adjust quoting if your SQL contains the chosen delimiter.

Repeatable tab-separated report

mysql -h db.example.net -u reporting -p analytics 
  --batch < daily_report.sql > daily_report.tsv

Keep daily_report.sql under your normal review and change-control process, and protect daily_report.tsv as exported database data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Final decision

Use an interactive mysql prompt when you are discovering a schema or refining SQL. Use --execute for a short, known statement that should run once and exit. Use a reviewed SQL file with --batch and input redirection when the work must be repeatable, captured, or consumed by another program. In every mode, enter the password through a prompt or protected credential configuration rather than placing it directly on the command line.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.