📄 query.sgml
字号:
<!--$Header: /cvsroot/pgsql/doc/src/sgml/query.sgml,v 1.34 2003/11/01 01:56:29 petere Exp $--> <chapter id="tutorial-sql"> <title>The <acronym>SQL</acronym> Language</title> <sect1 id="tutorial-sql-intro"> <title>Introduction</title> <para> This chapter provides an overview of how to use <acronym>SQL</acronym> to perform simple operations. This tutorial is only intended to give you an introduction and is in no way a complete tutorial on <acronym>SQL</acronym>. Numerous books have been written on <acronym>SQL</acronym>, including <xref linkend="MELT93"> and <xref linkend="DATE97">. You should be aware that some <productname>PostgreSQL</productname> language features are extensions to the standard. </para> <para> In the examples that follow, we assume that you have created a database named <literal>mydb</literal>, as described in the previous chapter, and have started <application>psql</application>. </para> <para> Examples in this manual can also be found in the <productname>PostgreSQL</productname> source distribution in the directory <filename>src/tutorial/</filename>. Refer to the <filename>README</filename> file in that directory for how to use them. To start the tutorial, do the following:<screen><prompt>$</prompt> <userinput>cd <replaceable>....</replaceable>/src/tutorial</userinput><prompt>$</prompt> <userinput>psql -s mydb</userinput><computeroutput>...</computeroutput><prompt>mydb=></prompt> <userinput>\i basics.sql</userinput></screen> The <literal>\i</literal> command reads in commands from the specified file. The <literal>-s</literal> option puts you in single step mode which pauses before sending each statement to the server. The commands used in this section are in the file <filename>basics.sql</filename>. </para> </sect1> <sect1 id="tutorial-concepts"> <title>Concepts</title> <para> <indexterm><primary>relational database</primary></indexterm> <indexterm><primary>hierarchical database</primary></indexterm> <indexterm><primary>object-oriented database</primary></indexterm> <indexterm><primary>relation</primary></indexterm> <indexterm><primary>table</primary></indexterm> <productname>PostgreSQL</productname> is a <firstterm>relational database management system</firstterm> (<acronym>RDBMS</acronym>). That means it is a system for managing data stored in <firstterm>relations</firstterm>. Relation is essentially a mathematical term for <firstterm>table</firstterm>. The notion of storing data in tables is so commonplace today that it might seem inherently obvious, but there are a number of other ways of organizing databases. Files and directories on Unix-like operating systems form an example of a hierarchical database. A more modern development is the object-oriented database. </para> <para> <indexterm><primary>row</primary></indexterm> <indexterm><primary>column</primary></indexterm> Each table is a named collection of <firstterm>rows</firstterm>. Each row of a given table has the same set of named <firstterm>columns</firstterm>, and each column is of a specific data type. Whereas columns have a fixed order in each row, it is important to remember that SQL does not guarantee the order of the rows within the table in any way (although they can be explicitly sorted for display). </para> <para> <indexterm><primary>database cluster</primary></indexterm> <indexterm><primary>cluster</primary><secondary>of databases</secondary><see>database cluster</see></indexterm> Tables are grouped into databases, and a collection of databases managed by a single <productname>PostgreSQL</productname> server instance constitutes a database <firstterm>cluster</firstterm>. </para> </sect1> <sect1 id="tutorial-table"> <title>Creating a New Table</title> <indexterm zone="tutorial-table"> <primary>CREATE TABLE</primary> </indexterm> <para> You can create a new table by specifying the table name, along with all column names and their types:<programlisting>CREATE TABLE weather ( city varchar(80), temp_lo int, -- low temperature temp_hi int, -- high temperature prcp real, -- precipitation date date);</programlisting> You can enter this into <command>psql</command> with the line breaks. <command>psql</command> will recognize that the command is not terminated until the semicolon. </para> <para> White space (i.e., spaces, tabs, and newlines) may be used freely in SQL commands. That means you can type the command aligned differently than above, or even all on one line. Two dashes (<quote><literal>--</literal></quote>) introduce comments. Whatever follows them is ignored up to the end of the line. SQL is case insensitive about key words and identifiers, except when identifiers are double-quoted to preserve the case (not done above). </para> <para> <type>varchar(80)</type> specifies a data type that can store arbitrary character strings up to 80 characters in length. <type>int</type> is the normal integer type. <type>real</type> is a type for storing single precision floating-point numbers. <type>date</type> should be self-explanatory. (Yes, the column of type <type>date</type> is also named <literal>date</literal>. This may be convenient or confusing -- you choose.) </para> <para> <productname>PostgreSQL</productname> supports the usual <acronym>SQL</acronym> types <type>int</type>, <type>smallint</type>, <type>real</type>, <type>double precision</type>, <type>char(<replaceable>N</>)</type>, <type>varchar(<replaceable>N</>)</type>, <type>date</type>, <type>time</type>, <type>timestamp</type>, and <type>interval</type>, as well as other types of general utility and a rich set of geometric types. <productname>PostgreSQL</productname> can be customized with an arbitrary number of user-defined data types. Consequently, type names are not syntactical key words, except where required to support special cases in the <acronym>SQL</acronym> standard. </para> <para> The second example will store cities and their associated geographical location:<programlisting>CREATE TABLE cities ( name varchar(80), location point);</programlisting> The <type>point</type> type is an example of a <productname>PostgreSQL</productname>-specific data type. </para> <para> <indexterm> <primary>DROP TABLE</primary> </indexterm> Finally, it should be mentioned that if you don't need a table any longer or want to recreate it differently you can remove it using the following command:<synopsis>DROP TABLE <replaceable>tablename</replaceable>;</synopsis> </para> </sect1> <sect1 id="tutorial-populate"> <title>Populating a Table With Rows</title> <indexterm zone="tutorial-populate"> <primary>INSERT</primary> </indexterm> <para> The <command>INSERT</command> statement is used to populate a table with rows:<programlisting>INSERT INTO weather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27');</programlisting> Note that all data types use rather obvious input formats. Constants that are not simple numeric values usually must be surrounded by single quotes (<literal>'</>), as in the example. The <type>date</type> type is actually quite flexible in what it accepts, but for this tutorial we will stick to the unambiguous format shown here. </para> <para> The <type>point</type> type requires a coordinate pair as input, as shown here:<programlisting>INSERT INTO cities VALUES ('San Francisco', '(-194.0, 53.0)');</programlisting> </para> <para> The syntax used so far requires you to remember the order of the columns. An alternative syntax allows you to list the columns explicitly:<programlisting>INSERT INTO weather (city, temp_lo, temp_hi, prcp, date) VALUES ('San Francisco', 43, 57, 0.0, '1994-11-29');</programlisting> You can list the columns in a different order if you wish or even omit some columns, e.g., if the precipitation is unknown:<programlisting>INSERT INTO weather (date, city, temp_hi, temp_lo) VALUES ('1994-11-29', 'Hayward', 54, 37);</programlisting> Many developers consider explicitly listing the columns better style than relying on the order implicitly. </para> <para> Please enter all the commands shown above so you have some data to work with in the following sections. </para> <para> <indexterm> <primary>COPY</primary> </indexterm> You could also have used <command>COPY</command> to load large amounts of data from flat-text files. This is usually faster because the <command>COPY</command> command is optimized for this application while allowing less flexibility than <command>INSERT</command>. An example would be:<programlisting>COPY weather FROM '/home/user/weather.txt';</programlisting> where the file name for the source file must be available to the backend server machine, not the client, since the backend server reads the file directly. You can read more about the <command>COPY</command> command in <xref linkend="sql-copy">. </para> </sect1> <sect1 id="tutorial-select"> <title>Querying a Table</title> <para> <indexterm><primary>query</primary></indexterm> <indexterm><primary>SELECT</primary></indexterm> To retrieve data from a table, the table is <firstterm>queried</firstterm>. An <acronym>SQL</acronym> <command>SELECT</command> statement is used to do this. The statement is divided into a select list (the part that lists the columns to be returned), a table list (the part that lists the tables from which to retrieve the data), and an optional qualification (the part that specifies any restrictions). For example, to retrieve all the rows of table <classname>weather</classname>, type:<programlisting>SELECT * FROM weather;</programlisting> (here <literal>*</literal> means <quote>all columns</quote>) and the output should be:<screen> city | temp_lo | temp_hi | prcp | date---------------+---------+---------+------+------------ San Francisco | 46 | 50 | 0.25 | 1994-11-27 San Francisco | 43 | 57 | 0 | 1994-11-29 Hayward | 37 | 54 | | 1994-11-29(3 rows)</screen> </para> <para> You may specify any arbitrary expressions in the select list. For example, you can do:<programlisting>SELECT city, (temp_hi+temp_lo)/2 AS temp_avg, date FROM weather;</programlisting> This should give:<screen> city | temp_avg | date---------------+----------+------------ San Francisco | 48 | 1994-11-27 San Francisco | 50 | 1994-11-29 Hayward | 45 | 1994-11-29(3 rows)</screen> Notice how the <literal>AS</literal> clause is used to relabel the output column. (It is optional.) </para> <para> Arbitrary Boolean operators (<literal>AND</literal>, <literal>OR</literal>, and <literal>NOT</literal>) are allowed in the qualification of a query. For example, the following retrieves the weather of San Francisco on rainy days:<programlisting>SELECT * FROM weather WHERE city = 'San Francisco' AND prcp > 0.0;</programlisting> Result:<screen> city | temp_lo | temp_hi | prcp | date---------------+---------+---------+------+------------ San Francisco | 46 | 50 | 0.25 | 1994-11-27(1 row)</screen> </para> <para> <indexterm><primary>ORDER BY</primary></indexterm> <indexterm><primary>DISTINCT</primary></indexterm> <indexterm><primary>duplicate</primary></indexterm> As a final note, you can request that the results of a query can be returned in sorted order or with duplicate rows removed:<programlisting>SELECT DISTINCT city FROM weather ORDER BY city;</programlisting><screen> city--------------- Hayward San Francisco(2 rows)</screen> <literal>DISTINCT</literal> and <literal>ORDER BY</literal> can be used separately, of course. </para> </sect1> <sect1 id="tutorial-join"> <title>Joins Between Tables</title> <indexterm zone="tutorial-join"> <primary>join</primary> </indexterm> <para> Thus far, our queries have only accessed one table at a time. Queries can access multiple tables at once, or access the same table in such a way that multiple rows of the table are being processed at the same time. A query that accesses multiple rows of the same or different tables at one time is called a <firstterm>join</firstterm> query. As an example, say you wish to list all the weather records together with the location of the associated city. To do that, we need to compare the city column of each row of the weather table with the name column of all rows in the cities table, and select the pairs of rows where these values match. <note> <para> This is only a conceptual model. The actual join may be performed in a more efficient manner, but this is invisible to the user. </para> </note> This would be accomplished by the following query:<programlisting>SELECT * FROM weather, cities WHERE city = name;</programlisting><screen> city | temp_lo | temp_hi | prcp | date | name | location---------------+---------+---------+------+------------+---------------+----------- San Francisco | 46 | 50 | 0.25 | 1994-11-27 | San Francisco | (-194,53) San Francisco | 43 | 57 | 0 | 1994-11-29 | San Francisco | (-194,53)(2 rows)</screen> </para> <para> Observe two things about the result set: <itemizedlist> <listitem> <para> There is no result row for the city of Hayward. This is
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -