📄 query.sgml
字号:
<!--$PostgreSQL: pgsql/doc/src/sgml/query.sgml,v 1.45 2005/06/13 02:40:06 neilc 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>. To use those files, first change to that directory and run <application>make</>:<screen><prompt>$</prompt> <userinput>cd <replaceable>....</replaceable>/src/tutorial</userinput><prompt>$</prompt> <userinput>make</userinput></screen> This creates the scripts and compiles the C files containing user-defined functions and types. (You must use GNU make for this — it may be named something different on your system, often <application>gmake</>.) Then, 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 standard <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" endterm="sql-copy-title">. </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> is a shorthand for <quote>all columns</quote>. <footnote> <para> While <literal>SELECT *</literal> is useful for off-the-cuff queries, it is widely considered bad style in production code, since adding a column to the table would change the results. </para> </footnote> So the same result would be had with:<programlisting>SELECT city, temp_lo, temp_hi, prcp, date FROM weather;</programlisting> 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 can write expressions, not just simple column references, 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. (The <literal>AS</literal> clause is optional.) </para> <para> A query can be <quote>qualified</> by adding a <literal>WHERE</> clause that specifies which rows are wanted. The <literal>WHERE</> clause contains a Boolean (truth value) expression, and only rows for which the Boolean expression is true are returned. The usual Boolean operators (<literal>AND</literal>, <literal>OR</literal>, and <literal>NOT</literal>) are allowed in the qualification. 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> You can request that the results of a query be returned in sorted order:<programlisting>SELECT * FROM weather ORDER BY city;</programlisting><screen> city | temp_lo | temp_hi | prcp | date---------------+---------+---------+------+------------ Hayward | 37 | 54 | | 1994-11-29 San Francisco | 43 | 57 | 0 | 1994-11-29 San Francisco | 46 | 50 | 0.25 | 1994-11-27</screen> In this example, the sort order isn't fully specified, and so you might get the San Francisco rows in either order. But you'd always get the results shown above if you do<programlisting>SELECT * FROM weather ORDER BY city, temp_lo;</programlisting> </para> <para> <indexterm><primary>DISTINCT</primary></indexterm> <indexterm><primary>duplicate</primary></indexterm> You can request that duplicate rows be removed from the result of a query:<programlisting>SELECT DISTINCT city FROM weather;</programlisting><screen> city--------------- Hayward San Francisco(2 rows)</screen> Here again, the result row ordering might vary. You can ensure consistent results by using <literal>DISTINCT</literal> and <literal>ORDER BY</literal> together: <footnote> <para> In some database systems, including older versions of <productname>PostgreSQL</productname>, the implementation of <literal>DISTINCT</literal> automatically orders the rows and so <literal>ORDER BY</literal> is redundant. But this is not required by the SQL standard, and current <productname>PostgreSQL</productname> doesn't guarantee that <literal>DISTINCT</literal> causes the rows to be ordered. </para> </footnote><programlisting>SELECT DISTINCT city FROM weather ORDER BY city;</programlisting> </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
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -