Querying a Database

In database terms, a query is used to retrieve data from the database.

Queries are one of the things that make databases so powerful. A "query" refers to the action of retrieving data from your database. Usually, you will be selective with how much data you want returned. If you have a lot of data in your database, you probably don't want to see everything. More likely, you'll only want to see data that fits a certain criteria.

For example, you might only want to see how many individuals in your database live in a given city. Or you might only want to see which individuals have registered with your database within a given time period.

As with many other tasks, you can query a database either programatically or via a user interface.

Option 1: Programatically

The way to retrieve data from your database with SQL is to use the SELECT statement.

Using the SELECT statement, you can retrieve all records...


...or just some of the records:

WHERE ArtistId = 1;

The 2nd query only returns records where the value in the ArtistId column equals 1. So if there are say, three albums belonging to artist 1, then three records would be returned.

SQL is a powerful language and the above statement is very simple. You can use SQL to choose which columns you want to display, you could add further criteria, and you can even query multiple tables at the same time. If you're interested in learning more about SQL, be sure to check out the SQL tutorial after you've finished this one!

Option 2: User Interface

You might find the user interface easier to generate your queries, especially if they are complex.

Database management systems usually offer a "design view" for your queries. Design view enables you to pick and choose which columns you want to display and what criteria you'd like to use to filter the data.

  • Screenshot of a database query in Datasheet View. Screenshot of a zoom-in of the same query.

    Designing a Query

    Here's an example of a query in Design View in Microsoft Access.

    When you run a query like this, the database system actually uses SQL (behind the scenes) to generate the query.

  • Screenshot of a database query result set.

    Query Results

    Regardless of the method you use to query the database, the results will usually be displayed in tabular format.