Connect to and Query Azure SQL Database

This tutorial guides you through the process of connecting to your Azure SQL Database and performing basic queries using common tools.

Ensure you have successfully created an Azure SQL Database and configured its firewall rules before proceeding.

Prerequisites

Connecting to Azure SQL Database

You can connect to your Azure SQL Database using various tools. Here are two common methods:

Method 1: Using Azure Data Studio

Azure Data Studio is a cross-platform database tool that runs on Windows, macOS, and Linux.

  1. Download and Install Azure Data Studio: If you haven't already, download Azure Data Studio from the official website and install it.
  2. Launch Azure Data Studio.
  3. Click New Connection.
  4. In the Connection details pane:
    • Connection type: Microsoft SQL Server
    • Server: Enter your server name (e.g., your-server-name.database.windows.net).
    • Authentication type: SQL Login
    • User name: Enter your SQL username.
    • Password: Enter your SQL password.
    • Database: Select your database from the dropdown or type its name.
    • Server Group: (Optional) Assign to a group.
  5. Click Connect.

Method 2: Using SQL Server Management Studio (SSMS)

SQL Server Management Studio (SSMS) is a comprehensive IDE for managing SQL Server.

  1. Download and Install SSMS: Download SSMS from the Microsoft documentation and install it.
  2. Launch SSMS.
  3. In the Connect to Server dialog:
    • Server type: Database Engine
    • Server name: Enter your server name (e.g., your-server-name.database.windows.net).
    • Authentication: SQL Server Authentication
    • Login: Enter your SQL username.
    • Password: Enter your SQL password.
  4. Click Connect.
For enhanced security, consider using Azure Active Directory authentication instead of SQL Login.

Querying Azure SQL Database

Once connected, you can execute SQL queries. Let's create a simple table and insert some data.

Creating a Sample Table

In your query editor window, run the following Transact-SQL (T-SQL) statements:


-- Create a new table named 'Products'
CREATE TABLE Products (
    ProductID INT PRIMARY KEY IDENTITY(1,1),
    ProductName VARCHAR(100) NOT NULL,
    Price DECIMAL(10, 2)
);

-- Insert sample data into the 'Products' table
INSERT INTO Products (ProductName, Price) VALUES
('Laptop', 1200.50),
('Keyboard', 75.00),
('Mouse', 25.99),
('Monitor', 300.75);
            

Querying Data

Now, retrieve the data from the 'Products' table:


-- Select all columns and rows from the Products table
SELECT ProductID, ProductName, Price
FROM Products;

-- Select products with a price greater than 100
SELECT ProductName, Price
FROM Products
WHERE Price > 100;
            

You should see the results of your queries displayed in the results pane of your chosen tool.

Next Steps

Congratulations! You have successfully connected to and queried your Azure SQL Database. You can now explore more advanced features such as: