Home > Articles > Data > SQL

An Introduction to SQL

  • Print
  • + Share This

Structured Query Language (SQL) is a database query language that was adopted as an industry standard in 1986. A major revision of the SQL standard, SQL2, was released in 1992. Its successor, SQL3, also contains object-oriented components. Currently, ANSI SQL92 is the most important standard.

This language enables you to pose complex questions to a database. It also provides a means of modifying databases. Many databases support SQL, so you can apply this knowledge to MS SQL Server, DB2, Oracle, PostgreSQL, and countless other databases.

This chapter is from the book

This chapter is from the book

Structured Query Language (SQL) is a database query language that was adopted as an industry standard in 1986. A major revision of the SQL standard, SQL2, was released in 1992. Its successor, SQL3, also contains object-oriented components. Currently, ANSI SQL92 is the most important standard.

This language enables you to pose complex questions to a database. It also provides a means of modifying databases. SQL is widely used. Many databases support SQL, which means that if you learn how to use SQL, you can apply this knowledge to MS SQL Server, DB2, Oracle, PostgreSQL, and countless other databases. SQL works with relational databases, which store data in objects. An object can be a table, for example. A database is a collection of tables and functions. A table consists of a list of records; each record (row) in a table has the same structure and each has a fixed number of fields (columns) of a given type. SQL can be used to communicate with a database and its components.

Every database has a slightly different version of SQL implemented, so it can sometimes be very hard to port applications from one database to another. For that reason, ANSI SQL92 has been developed. ANSI SQL92 is a standard that should be understood by every database supporting SQL. Unfortunately, many commercial database developers don't implement fully ANSI SQL92–compatible SQL engines in their databases.

PostgreSQL developers are working hard to make PostgreSQL 100% ANSI SQL–compatible. Therefore, PostgreSQL applications are portable and easy to understand.

For further information about the ANSI SQL92 standard or any other ANSI standard, check out http://www.ansi.org.

Relational Databases and Their Components

The relational database model was conceived by E. F. Codd in 1969. The model is based on branches of mathematics called set theory and predicate logic. The main idea is that a database consists of various unordered tables called relations that can be modified by the user. Relational databases were a major improvement to traditional database systems, which were not as flexible and sometimes hardware-dependent.

Relational databases consist of various components. This chapter provides basic insight to those who have not dealt with relational databases, and is not a tutorial about the theory behind relational databases.

Tables and Keys

Tables are the key components of relational databases. A relational database consists of one or more tables used to store information. A table consists of rows. Every row is divided into fields (columns) that have a certain datatype.

Assume you have a table used to store names and salaries (see Figure 3.1). A row containing this information consists of two fields: one for the name and one for the salary. If information from various tables has to be collected by a query, a join is performed by the database. Joins are covered extensively later in this chapter (see the section "Joining Tables").

Primary Keys

Every table should have a primary key. In this case, the name would be a useful primary key if the names are unique. Primary keys have to be fields that contain unique values—a primary key is the identifier of a record (row).

Keys have a significant impact on performance, but are also needed to guarantee data integrity.

Figure 3.1 A simple table with four columns.

Foreign Keys

Foreign keys are keys "taken" from a different table. Imagine a database with two tables. In one table, we store information about companies, such as the name and the location of each company. In the second table, we store information about the employees of the companies stored in the first table. We use a foreign key to make sure that the second table cannot contain information about employees who do not work for one of the companies listed in the first table. The behavior of PostgreSQL when dealing with foreign keys can be defined for every table. It can be defined, for instance, that all employees in the second table are removed when a company is removed from the first table. Rules defining PostgreSQL's behavior are called integrity constraints.

Foreign keys are extremely useful when working with complex data models and are usually used to protect data integrity. See Figure 3.2 for an example of two tables connected with a foreign key.


Every column in a table must have a datatype. The user's job is to find the best datatype for storing a certain piece of information in the database. Let's assume that we want to store the name of a person. Names are character strings of undefined length. A suitable datatype for names would be varchar(50). In this example, 50 is the maximum length of the field. A varchars is stored efficiently in the database, because only the actual length of the field—and not the maximum length of the varchar— is used to store the text.

Figure 3.2 Connecting tables using a foreign key.

PostgreSQL offers a variety of datatypes. Here is an overview of all datatypes available in PostgreSQL 7.0.3:

xy=# \dT
List of types

  Type  |              Description
 SET    | set of tuples
 abstime  | absolute, limited-range date and time (Unix system time)
 aclitem  | access control list
 bit    | fixed-length bit string
 bool   | boolean, 'true'/'false'
 box    | geometric box '(lower left,upper right)'
 bpchar  | char(length), blank-padded string, fixed storage length
 bytea   | variable-length string, binary values escaped
 char   | single character
 cid    | command identifier type, sequence in transaction id
 cidr   | network IP address/netmask, network address
 circle   | geometric circle '(center,radius)'
 date    | ANSI SQL date
 filename  | filename used in system tables
 float4   | single-precision floating point number, 4-byte storage
 float8   | double-precision floating point number, 8-byte storage
 inet    | IP address/netmask, host address, netmask optional
 int2    | -32 thousand to 32 thousand, 2-byte storage
 int2vector | array of 16 int2 integers, used in system tables
 int4    | -2 billion to 2 billion integer, 4-byte storage
 int8    | ~18 digit integer, 8-byte storage
 interval  | @ <number> <units>, time interval
 line    | geometric line '(pt1,pt2)'
 lseg    | geometric line segment '(pt1,pt2)'
 lztext   | variable-lengthstring, stored compressed
 macaddr  | XX:XX:XX:XX:XX,MAC address
 money   | $d,ddd.cc,money                          
 name    | 31-character type for storing system identifiers
 numeric  | numeric(precision, decimal), arbitrary precision number
 oid    | object identifier(oid), maximum 4 billion
 oidvector | array of 16 oids, used in system tables
 path    | geometric path '(pt1,...)'
 point   | geometric point '(x, y)'
 polygon  | geometric polygon '(pt1,...)'
 regproc  | registered procedure
 reltime  | relative, limited-range time interval (Unix delta time)
 smgr    | storage manager
 text    | variable-length string, no limit specified
 tid    | (Block, offset), physical location of tuple
 time    | hh:mm:ss, ANSI SQL time
 timestamp | date and time
 timetz   | hh:mm:ss, ANSI SQL time
 tinterval | (abstime,abstime), time interval unknown  |
 varbit   | fixed-length bit string
 varchar  | varchar(length), non-blank-padded string, variable storage length
 xid    | transaction id
(47 rows)                      

You can see that PostgreSQL offers powerful datatypes for nearly any purpose you can imagine. Thanks to PostgreSQL's modularity, new datatypes can easily be added to this list. The CREATE TYPE command can be used to add a datatype.

The most important datatypes are covered extensively later in this chapter. You will learn how to use these datatypes efficiently in real-life scenarios.


Indices are used to speed up searching. Let's assume you have a telephone directory containing 1,000,000 records consisting of two fields. The first field contains the name of a person, and the second field contains the phone number. If someone wants to know the phone number of a certain person, the database runs a sequential scan, which means that every record is scanned for the requested name. On average, a query such as that needs 500,000 (1,000,000 divided by 2) steps to find the result. If tables are large, the performance of the database system decreases significantly.

In this case, an index can be defined on a column. An index is, in most cases, a tree, and the leaves of the tree point to a data object.

Before you look at PostgreSQL's implementations of indices, let's explore the basic idea of indexing using B-trees.

B-trees are an efficient data structure for retrieving values in tables. Trees provide the data sorted so that values can be accessed much faster. In a B-tree, the tree consists of nodes, with up to two children. A child can be a node for up to two more children. Nodes are values in the data that are the parents of other values. A child that has no children is called a leaf. The data structure looks like a tree, but it's upside down.

B-trees are used to search efficiently for a value in a data structure. If the number of values stored in a tree doubles, the time to search for a value doesn't double—it takes one additional step. If the number of values stored in a tree is 1,024 times higher, it takes only 10 additional steps to find a value, because 1,024 is the result of 210.

Imagine 1,048,576 (unique) datasets. It would take 20 (logarithmus dualis: 20 = ld 1,048,576) steps to find the right value. In this example, you can see how an index can speed up your query; if no index is used to find the right value out of 1,048,576, the database needs 524,288 steps (1,048,576 divided by 2) to find the result.


This works only as long as the B-tree is 100% balanced (see Figure 3.3).

In databases, B+ trees are usually used instead of B-trees, because B+ trees guarantee higher performance in real-world scenarios. The Reiser Filesystem (a Linux Filesystem) is also based on balanced B+ trees.

PostgreSQL supports three types of indices:

  • B-tree

  • R-tree

  • Hash access

Figure 3.3 A balanced B-tree.


As mentioned in the last section, one way of indexing a column in PostgreSQL is to use a B-tree. PostgreSQL doesn't use "ordinary" B-trees for indexing because some additional features are required that can't be implemented with ordinary B-trees. One of the problems has to do with index locking. Assume that one user adds data to an index while a second user does an index scan. User two needs a fixed and persistent "image" of the index while performing the query. This problem can be solved with the help of a Lehman-Yao high-concurrency btree. This kind of tree is a super-high–concurrency solution at the expense of a little extra complexity in the data structure. The following changes have to be made in the data structure:

  • Use a B+ tree (sometimes called a B* tree).

  • Add high keys to each page.

  • Add right links to each page.

  • Scan index from top to bottom and left to right.

  • Insert from bottom to top.

This ensures that no locking for reading is required and lock coupling for writes is rare.


R-trees use Guttman's quadratic split algorithm and are a dynamic index structure for spatial searching. Traditional indexing algorithms are not suitable for computer-aided design or geo-applications. Because PostgreSQL offers many datatypes that can be used for spatial calculations, R-trees can be a powerful method of speeding up your applications.

To understand spatial queries, imagine a situation where you want to find all countries that have land within 100 miles of a specific location. R-trees can be used to solve the problem for the database efficiently. R-trees are highly balanced trees and can be compared with B-trees. PostgreSQL offers a variety of operators for working with geo-data. In most cases, the user does not need to care about the details.

Hash Access Methods

The linear hashing algorithm used by PostgreSQL was developed by W. Litwin for disk-based systems with one processor. Linear hashing allows dynamic reorganization of a hashed database when records are inserted or updated. The possibility of accessing one record with one-bucket access should be maintained. Linear hashing enables the hashing function to be changed while the database is changed; only a small part of the database is affected when the hash function is changed.

Concurrent linear hashing adds a locking protocol and allows simultaneous access.


Sequences are a comfortable method for building lists that are numbered consecutively. A sequence can be used in the entire database (if all users have access to the sequence). Every time a user accesses the sequence, the value of the sequence is incremented. It is guaranteed that a certain number is used only once. Sequences can therefore be used to create unique numbers. The user does not have to care about transactions when dealing with sequences, because the database makes sure that every value is used only once internally.


Powerful and comfortable applications can be built with the help of triggers, which are used to start certain functions after certain events. Triggers are defined for tables and have to be associated with an event such as INSERT or UPDATE.

In real-world scenarios, triggers are used to perform operations automatically, but triggers are also used for many purposes by the database internally.

You will explore triggers extensively in Chapter 5, "Understanding Transactions," which is about PL/pgSQL.


Object relational databases consist of objects. Object orientation is an extension to the relational database model and is, in the case of PostgreSQL, a very powerful feature. Objects offer important core features, as explained in the following sections.


A class is a named collection of object instances. Each instance has a unique object identifier (OID).


Each OID is unique in the entire system.

Classes can be created using the CREATE command. Various versions of a class are called instances. In case of object relational databases, an instance can be a row in a table.


Inheritance means that a class can inherit functions or attributes from a class that is "higher" in the hierarchy. If a new class is derived from one of those upper classes, it inherits all information from the upper class. It is now possible to implement additional features for the new class.


Features defined for a derived class are not visible in the parent class.

Here is an example of how to make the inheritance process clearer:

Imagine a table containing information about cars. We define a class that stores all information about a car that is common for cars, such as the color or the year the car was built. Now we define a class for a specific type of car that is used to store additional information, such as technical data about the air conditioning. The class defined for the specific type of car inherits all information from the parent type storing information about ordinary cars.

You learn how to query derived tables later in the book.

Function Overloading

Function overloading is a key feature of object-oriented systems. In function overloading, many versions of a function can exist. The difference between those functions is the number of parameters that can be passed to it. Assume a function called sum() used to sum numbers. Summing can be useful for 2, 3, or more values. With function overloading, you can implement functions for each of the cases.

PL/pgSQL supports function overloading, and you will soon recognize it as a powerful and easy-to-use feature. Function overloading can also lead to dangerous bugs that are sometimes very hard to track down, because the programmer has to find the correct version of the function that was used before looking for the real error in the source code.


If you want to look at your data from a broader perspective, views might be a good choice. A view is a virtual table that contains information from other tables. A view is nothing else than the result of a SELECT statement presented as a virtual table by the database system. Views can be used to simplify SQL statements.


Procedures are functions that are stored directly within the database. Many database systems offer embedded languages. Oracle databases, for instance, offer a language called PL/SQL. PostgreSQL offers a language called PL/pgSQL, which is similar to PL/SQL and also very powerful. PostgreSQL offers even more programming interfaces, but PL/Tcl and PL/Perl are the most important ones to mention here. Writing procedures will be a major part of the chapter about PL/pgSQL.

Aggregate Functions and Aggregate Expressions

The capability of performing aggregations is an important feature of SQL. It enables the user to perform tasks on more than just one record.

Aggregate Functions

Aggregate functions are used to perform data calculations, such as maximum, minimum, or average. Aggregate functions can easily be added to PostgreSQL by using the CREATE AGGREGATE command. Many functions are already included in the base distribution, but it can be extremely useful to add your own features.

Aggregate Expressions

Aggregate expressions are used to perform operations with multiple lines returned by a SELECT statement. The DISTINCT command is a good example of an aggregate expression. If multiple rows contain the same data, DISTINCT returns multiple entries only once. Assume a query where you want to retrieve all names from a table and you want each name to be returned only once. The DISTINCT command is the solution.

  • + Share This
  • 🔖 Save To Your Account