Use Ruby to query an Azure SQL database

This quickstart demonstrates how to use Ruby to create a program to connect to an Azure SQL database and use Transact-SQL statements to query data.


To complete this quickstart, make sure you have the following prerequisites:

  • A server-level firewall rule for the public IP address of the computer you use for this quickstart.

  • You have installed Ruby and related software for your operating system:

    • MacOS: Install Homebrew, install rbenv and ruby-build, install Ruby, and then install FreeTDS. See Step 1.2, 1.3, 1.4, and 1.5.
    • Ubuntu: Install prerequisites for Ruby, install rbenv and ruby-build, install Ruby, and then install FreeTDS. See Step 1.2, 1.3, 1.4, and 1.5.

SQL server connection information

Get the connection information needed to connect to the Azure SQL database. You will need the fully qualified server name, database name, and login information in the next procedures.

  1. Sign in to the Azure portal.
  2. Select SQL Databases from the left-hand menu, and click your database on the SQL databases page.
  3. On the Overview page for your database, review the fully qualified server name as shown in the following image. You can hover over the server name to bring up the Click to copy option.


  4. If you forget your server login information, navigate to the SQL Database server page to view the server admin name. If necessary, reset the password.


You must have a firewall rule in place for the public IP address of the computer on which you perform this tutorial. If you are on a different computer or have a different public IP address, create a server-level firewall rule using the Azure portal.

Insert code to query SQL database

  1. In your favorite text editor, create a new file, sqltest.rb

  2. Replace the contents with the following code and add the appropriate values for your server, database, user, and password.

require 'tiny_tds'
server = ''
database = 'your_database'
username = 'your_username'
password = 'your_password'
client = username: username, password: password, 
    host: server, port: 1433, database: database, azure: true

puts "Reading data from table"
tsql = "SELECT TOP 20 pc.Name as CategoryName, as ProductName
        FROM [SalesLT].[ProductCategory] pc
        JOIN [SalesLT].[Product] p
        ON pc.productcategoryid = p.productcategoryid"
result = client.execute(tsql)
result.each do |row|
    puts row

Run the code

  1. At the command prompt, run the following commands:

    ruby sqltest.rb
  2. Verify that the top 20 rows are returned and then close the application window.

Next Steps