Connect to and Query Azure SQL Database

This tutorial guides you through connecting to your Azure SQL Database and performing basic queries using popular tools and programming languages.

Prerequisites:
  • An Azure subscription.
  • An Azure SQL Database instance created.
  • Server firewall rules configured to allow access from your IP address.
  • Your SQL server admin login and password.

Using SQL Server Management Studio (SSMS)

SSMS is a powerful and popular tool for managing SQL Server databases.

Download and Install SSMS

If you don't have SSMS installed, download it from the official Microsoft SQL Server website.

Connect to your Azure SQL Database
  1. Open SSMS.
  2. In the "Connect to Server" dialog box, enter your fully qualified server name (e.g., your-server-name.database.windows.net).
  3. Select "SQL Server Authentication" for the Authentication type.
  4. Enter your SQL server admin Login name and Password.
  5. Click "Connect".

Connection Details Form (Example)

Execute Queries

Once connected, you can open a new query window (File > New > Query) and execute SQL statements:

SELECT TOP 10 * FROM dbo.Orders;
-- Get the count of customers in the 'SalesLT' schema
SELECT COUNT(*) FROM SalesLT.Customer;

Using Azure Data Studio

Azure Data Studio is a cross-platform database tool for data professionals.

Download and Install Azure Data Studio

Download it from the official Azure Data Studio website.

Connect to your Azure SQL Database

Click the "New Connection" button and fill in the connection details similar to SSMS.

Execute Queries

Open a new query editor and write your SQL commands.

SELECT Name, ListPrice FROM Production.Product WHERE ListPrice > 100;

Using Programming Languages

You can also connect and query your database programmatically.

Example: Python with `pyodbc`

Install `pyodbc`
pip install pyodbc
Write Python Code

Replace placeholders with your actual connection details.

import pyodbc

server = 'your-server-name.database.windows.net'
database = 'your-database-name'
username = 'your-username'
password = 'your-password'
driver = 'ODBC Driver 17 for SQL Server' # Or your installed driver

connection_string = f'DRIVER={{{driver}}};SERVER={server};DATABASE={database};UID={username};PWD={password}'

try:
    conn = pyodbc.connect(connection_string)
    cursor = conn.cursor()

    # Execute a query
    cursor.execute("SELECT @@VERSION;")
    row = cursor.fetchone()
    while row:
        print(row[0])
        row = cursor.fetchone()

    # Example query with results
    cursor.execute("SELECT TOP 5 Name, ListPrice FROM Production.Product;")
    rows = cursor.fetchall()
    for r in rows:
        print(f"Product: {r.Name}, Price: {r.ListPrice}")

except pyodbc.Error as ex:
    sqlstate = ex.args[0]
    print(f"Error connecting or querying: {sqlstate}")
finally:
    if conn:
        conn.close()
        print("Connection closed.")

Troubleshooting

Next Steps: