The SQL SELECT Statement

A relational database consists of rectangular tables with rows and columns. A SELECT statement can be used by a Java application to to extract some of the information in a table and place it in a ResultSet object. This object can be used to display or further process the data. Here are some examples of SQL statements extracting information from the Kids database, which contains the single table Roster.
  1. SELECT * FROM Roster
    Select all rows and columns from the table Roster.

  2. SELECT Name FROM Roster
    Select all rows, but only the column Name.

  3. SELECT Name, Age FROM Roster
    Select all rows and the columns Name and Age.

  4. SELECT * FROM Roster WHERE Name = 'Chloe'
    Select all columns, but only the row with the name Chloe.

  5. SELECT Name FROM Roster WHERE ID = 8630
    Select the name with the ID 8630.

  6. SELECT * FROM Roster WHERE Gender = 'F' and Age = 9
    Select all columns and only the rows with Gender F and Age 9.
Sometimes, an SQL must be constructed from information supplied at runtime. Suppose that you want to select all columns from the table where the name is supplied in the textfield called kidName. Here is what you do:

SQL = "SELECT * FROM Roster WHERE Name = '" + kidName.getText() + "'"

Note that text constants in SQL must be enclosed in single quotes, even when the text constant is obtained from a variable at run time.