How to Query a Database Using SELECT With MySQL

The most basic operation in any SQL system is the SELECT query. In MySQL, programmers use SELECT to query a database in order to retrieve records. Using SELECT will return a number of rows from a database based on the criteria you pass it. The command can be basic or complicated depending on how enhanced your SELECT statements are.

Instructions

    • 1

      Gather some basic information about the data you want. Know what information the database hold as well as which table you want to query, what rows the table holds and which of those rows you want to see.

    • 2

      Start with a very simple query which can then be built upon. This query will return every column and every row of the "customers" table, showing the basic form of the SELECT command. The amount of data returned will be overwhelming if your customer table is large. Example:
      SELECT * FROM customers;

    • 3

      Define what it is you want to do with the information your query will return. Remember, you won't usually need all columns of data.

    • 4

      Return only wanted columns. To return only a few columns, replace the asterisk in the previous command with a comma-separated list of columns you want. For example, if you're doing a mailing to all of your customers, you will only need the name and address columns. Example:
      SELECT name,address FROM customers;

    • 5

      Narrow your query further by returning only rows that interest you, using a WHERE clause. The WHERE clause will cause the SELECT query to return only rows that satisfy the WHERE clause. This query will select the name, address and balance of every row in the database with a negative balance. Example:
      SELECT name,address,balance FROM customers WHERE balance < 0;

    • 6

      Use the boolean OR and AND with the WHERE clause to join any number of conditions. The conditions can be as complicated or simple as you need them to be. It's dependent on how specific you want the return to be. Here AND is used so that the query will select not only the name and address of everyone with a positive balance, but also those whose name is 'Joe Smith'. Example:
      SELECT name,address FROM customers WHERE balance > 0 AND name = 'Joe Smith';

Tips & Warnings

  • In MySQL, as in other programming languages, the asterisk (

  • ) is a wild card used as a shortcut to return all the columns from a table.

Related Searches:

Comments

You May Also Like

Related Ads

Featured