Полезная информация

next up previous contents index
Next: WHERE Clause Up: Five Basic SQL Commands Previous: Adding Data with INSERT

Viewing Data with SELECT

You have seen how to store data in the database. Let's show you how to retrieve data. Surprisingly, there is only one command to get data out of the database, and that command is SELECT. You have already used SELECT in your first database query in figure [*] on page [*]. SELECT has many variations. We are going to use it to show the rows in the table friends. The query is shown in figure [*].

Figure: My first SELECT
...vert Allentown~~~~~~\vert PA~~~\vert~22
\par (3~rows)\end{list}\par

In this case, I put the entire query on one line. That's fine. As queries get longer, breaking them into multiple lines helps make things clearer.

Let's look at this in detail. First, we have the word SELECT, followed by an asterisk (*), then the word FROM, and our table name friends, and a semicolon to execute the query. The SELECT starts our command, and tells the database server what is coming next. The * tells the server we want all the column from the table. The FROM friends tells which table we want to see. So, we have said we want all (*) columns from our table friends, and indeed, that is what is displayed. It should have the same data as table [*] on page [*].

As I mentioned, SELECT has a large number of variations, and we will look at a few of them now. First, suppose you wanted to retrieve only one of the columns from the friends table. You may already suspect that theasterisk (*) has to be changed in the query. If you replace the asterisks (*) with one of the column names, you will see only that column. Try SELECT city FROM friends. You can choose any of the columns. You can even choose multiple columns, by separating the names with a comma. For example, to see first and last names only, use SELECT firstname, lastname FROM friends. Try a few more until you get comfortable. If you specify a name that is not a valid column name, you will get an error message, ERROR: attribute 'mycolname' not found. If you try selecting from a table that does not exist, you will get an error message, ERROR: Relation 'mytablename' does not exist. POSTGRESQL is using the proper relational database terms relation and attribute in these error messages.

next up previous contents index
Next: WHERE Clause Up: Five Basic SQL Commands Previous: Adding Data with INSERT
Bruce Momjian