Home > Articles > Data > SQL

An Introduction to SQL

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.

Datatypes

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

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.

Note

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.

B-Trees

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

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

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.

Triggers

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.

Objects

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.

Classes

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

Note

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

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.

Note

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.

Views

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

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020