To run SQL commands via the command line on Windows, you need a database system like Microsoft SQL Server, MySQL, or PostgreSQL installed and configured with its command-line client. Once set up, you launch the appropriate client tool (e.g., sqlcmd for SQL Server, mysql for MySQL) from Command Prompt or PowerShell, then enter and execute SQL statements. This guide covers the most common setup: using Microsoft SQL Server Command Line Tools.
What You'll Need
- Microsoft SQL Server installed (Express edition is free and sufficient for most users)
- SQL Server Command Line Tools (sqlcmd utility) — included in SQL Server Management Studio (SSMS) install or downloadable separately via the Command Line Utilities 18 for SQL Server package
- Windows Command Prompt or PowerShell (both work)
- Authentication credentials: either SQL Server login (username/password) or Windows Authentication (your Windows user account must have permissions)
- Network or local access to the SQL Server instance (default instance name:
localhostor.)
Step-by-Step
- Confirm the SQL Server service is running: Press
Win + R, typeservices.msc, and press Enter. In the Services window, locate SQL Server (MSSQLSERVER) (or SQL Server (InstanceName) for named instances). Ensure its Status is Running. If not, right-click and select Start. - Open Command Prompt or PowerShell: Press
Win, typecmdorpowershell, then press Enter. For this guide, we use Command Prompt, but commands are nearly identical in PowerShell. - Launch sqlcmd: At the command prompt, type one of the following and press Enter:
- For Windows Authentication (recommended for local dev):
sqlcmd -S localhost - For SQL Server Authentication (requires username/password):
sqlcmd -S localhost -U sa -P YourStrongPassword123!
ReplaceYourStrongPassword123!with your actual password. Avoid using thesaaccount in production; create a dedicated user instead.
1>, indicating sqlcmd is ready for input. - For Windows Authentication (recommended for local dev):
- Enter and execute a basic SQL command: Type a SQL statement ending with
GOon a new line. For example:SELECT 'Hello from SQL Server!' AS Message; GO
Press Enter after each line. The result should display the message in tabular format, followed by a new command prompt. - Run a more complex query: To create and query a test table:
CREATE DATABASE TestDB; GO USE TestDB; GO CREATE TABLE Users (Id INT, Name NVARCHAR(50)); GO INSERT INTO Users VALUES (1, 'Alice'), (2, 'Bob'); GO SELECT * FROM Users; GO
EachGOsends the preceding batch to the server. Results appear after the finalGO. - Exit sqlcmd: Type
EXITat the prompt and press Enter, or simply close the Command Prompt window.
Common Mistakes
- Forgetting
GO: sqlcmd won’t execute your query until it seesGOon its own line. Omitting it causes the prompt to wait indefinitely for more input. - Typo in server name: Using
localhost\SQLEXPRESSwhen your instance is namedMSSQLSERVER(or vice versa). Check the instance name in Services (see Step 1) or runsqlcmd -Lto list available local servers. - Password exposure: Passing passwords via
-Pon the command line leaves them visible in command history and Task Manager. Use-Pwithout a value (-P) to be prompted interactively instead. - Missing sqlcmd: The utility isn’t installed by default with SQL Server Engine alone. You must install the Command Line Utilities package separately or via SSMS.
- Firewall blocking: If connecting to a remote SQL Server, Windows Firewall may block port 1433 (default). Allow the port or enable SQL Browser service for named instances.
Tips
- Save scripts: Write your SQL in a text file (e.g.,
query.sql) and run it usingsqlcmd -S localhost -i query.sql. This avoids retyping long commands. - Use
-Efor trusted connections: Instead of omitting authentication flags, explicitly usesqlcmd -S localhost -Eto force Windows Authentication. - Enable
SET NOCOUNT ONfor scripts: AddSET NOCOUNT ON;at the top of your script to suppress row-count messages and reduce clutter in output. - Check version compatibility: sqlcmd version 18+ requires .NET Framework 4.8 or later. Run
sqlcmd -?to verify the installed version. - Use PowerShell for automation: In PowerShell, you can chain commands like
sqlcmd -S localhost -Q "SELECT GETDATE();"to run a query and exit immediately.
Troubleshooting
If sqlcmd doesn’t launch or the connection fails, follow these checks in order:
- Is
sqlcmdrecognized? If you see 'sqlcmd' is not recognized as an internal or external command, the utility isn’t in your PATH. Reinstall the Command Line Utilities package, ensuring the Add to PATH option is selected during setup. Alternatively, navigate toC:\Program Files\Microsoft SQL Server\180\Tools\Binn\(or similar) and runsqlcmd.exedirectly. - Can your machine reach SQL Server? Test connectivity with
telnet localhost 1433. If the screen goes blank, the port is open. If you get Connection failed, SQL Server may not be listening on TCP/IP. Open SQL Server Configuration Manager > SQL Server Network Configuration > Protocols for [Instance], and ensure TCP/IP is Enabled. Restart the SQL Server service afterward. - Login failed errors: A message like Login failed for user 'sa' usually means the password is wrong, or SQL Authentication isn’t enabled. To fix: In SSMS, right-click the server > Properties > Security, and ensure SQL Server and Windows Authentication mode is selected. Then restart the SQL Server service.
- Timeout or connection reset: If the command hangs or times out, verify the SQL Server Browser service is running (for named instances) and that your firewall allows SQL traffic. Also confirm you’re using the correct server name and instance (e.g.,
localhost\SQLEXPRESSvslocalhost). - Permission denied: Even with Windows Authentication, your user account may lack database access. Grant permissions in SSMS under Security > Logins, right-click your user > Properties > User Mapping, and select the target database with db_datareader or db_datawriter roles.
Frequently Asked Questions
Can I use MySQL or PostgreSQL command line instead?
Yes. For MySQL, install the MySQL Server or MySQL Command Line Client, then runmysql -u root -p. For PostgreSQL, use psql -U postgres after installing PostgreSQL. The steps are similar: launch the client, authenticate, then type queries ending with a semicolon (;) instead of GO.
How do I run a SQL script file from the command line?
Use the-i flag with sqlcmd: sqlcmd -S localhost -E -i C:\scripts\myscript.sql. To save output to a file, add -o C:\scripts\output.txt.
Do I need SQL Server Management Studio (SSMS) installed?
No. SSMS is a GUI tool and optional. The command-line tools (sqlcmd) can be installed independently via the Command Line Utilities 18 for SQL Server package from Microsoft’s official site.Why does sqlcmd ask for a password even when I used Windows Authentication?
If you omit-U and -P, sqlcmd defaults to Windows Authentication and shouldn’t prompt for a password. If it does, double-check your command syntax—ensure you didn’t accidentally include -U (which triggers SQL Authentication mode).
Is it safe to use the 'sa' account in scripts?
No. Thesa account has full administrative privileges. For automation or scripts, create a dedicated login with minimal required permissions (principle of least privilege) to reduce security risk.
Can I run sqlcmd remotely on another machine?
Yes, but you must specify the remote server name instead oflocalhost (e.g., sqlcmd -S RemotePC\SQLEXPRESS -U sa -P password). Ensure the remote SQL Server allows remote connections (enabled in SSMS server properties), and the firewall permits traffic on port 1433 (or the dynamic port for named instances).