SQL SELECT statement

Tuple

A SELECT statement can specify more than one value separated by a comma.

The query below selects a string literal, a numeric literal, and an arithmetic expression:

SELECT 'Alice', 170, 170*0.393701;

Such a set of values (attributes, fields) is called a tuple (a record, a row). 

Alias

In SQL, assigning an alias to each attribute of the tuple is essential when creating a query. You can achieve this by using the AS keyword followed by the name you want to give to the attribute value. When the alias consists of multiple words or matches an SQL keyword, you must enclose it in double quotes. Remember to apply aliases in all your queries to ensure accurate and efficient result representation. The following query demonstrates the proper use of aliases:

SELECT 
  'Alice' AS name, 
  170 AS height_in_centimeters, 
  170*0.393701 AS "height in inches"
;

The query evaluation result is a tuple with three attributes: name, height_in_centimeters, and height in inches. 

SQL is designed to process data organized in tables. The result of the example query is also a table with column names specified in aliases and consisting of only one row.

Code readability

One important feature of SQL is that it is case-insensitive, meaning that keywords may be written in any case. However, to improve code readability and emphasize the importance of specific keywords, it is common practice to write them in uppercase. Therefore, while writing SELECT, select, SeLeCt, and seLEct is technically valid, using uppercase letters for SQL keywords whenever possible.

It is recommended to use indentation, which leaves a bit of free space to separate the lines visually. 

Compare the following formatting options of the same query. Which one is easier to read?

SELECT 'Bob' AS name, 160 AS "height in centimeters", 160*0.393701 AS "height in inches";

SELECT 
  'Bob' AS "name", 
  160 AS "height in centimeters", 
  160*0.393701 AS "height in inches"
;

SELECT 
  'Bob'        AS "name", 
  160          AS "height in centimeters", 
  160*0.393701 AS "height in inches"
;

In the third version, it is much easier to see the number of attributes, their values, and their names. The version in the middle is intermediate in terms of code readability but easier to edit than the third one (manual indentation by blanks gets broken each time one changes the code). 

Basic SELECT statement

Here is a template for a basic SELECT statement: the SELECT keyword, a list of values to extract with optional aliases for them, and a semicolon to indicate the end of the statement:

SELECT val1 [AS name1], ..., valN [AS nameN];

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate