SQL SELECT Statement

previous next


The SQL SELECT Statement

The SELECT statement is used to select data from a table. The tabular result is stored in a result table (called the result-set).

Syntax

SELECT columnName(s) FROM tableName;

Note: SQL statements are not case sensitive. SELECT is the same as select.


SQL SELECT Example

To select the content of columns named "Title", "Author", and "Year", from the database table called "Books", we use a SELECT statement like this:

SELECT Title, Author, Year FROM Books;

The database table "Books":

Title

Author

Publisher

Year

الدورة الدموية

إبن النفيس

دار العلم

1650

Java 2

L. Johnston

Fast Press

2002

Linux and Unix

J. Sam

Fast Press

2004

Linux Distributions

J. Sam

Fast Press

2003

Operating Systems

M. Stone

Coriolis

2005

The result is:

Title

Author

Year

الدورة الدموية

إبن النفيس

1650

Java 2

L. Johnston

2002

Linux and Unix

J. Sam

2004

Linux Distributions

J. Sam

2003

Operating Systems

M. Stone

2005

 


Select All Columns

To select all columns from the "Books" table, we use a * symbol instead of column names, like this: 

SELECT * FROM Books;

The result is:

Title

Author

Publisher

Year

الدورة الدموية

إبن النفيس

دار العلم

1650

Java 2

L. Johnston

Fast Press

2002

Linux and Unix

J. Sam

Fast Press

2004

Linux Distributions

J. Sam

Fast Press

2003

Operating Systems

M. Stone

Coriolis

2005

 


The SELECT DISTINCT Statement

The DISTINCT keyword is used to return only distinct (different) values.

The SELECT statement returns information from table columns. But what if we only want to select distinct elements?

With SQL, all we need to do is to add a DISTINCT keyword to the SELECT statement:

Syntax

SELECT DISTINCT columnName(s) FROM tableName;

 


Using the DISTINCT keyword

To select ALL values from the column named "Publisher" we use a SELECT statement like this:

SELECT Publisher FROM Books;

The result is:

Publisher

دار العلم

Fast Press

Fast Press

Fast Press

Coriolis

 Note that "Fast Press" is listed trice in the result-set.

To select only DIFFERENT values from the column named "Publisher" we use a SELECT DISTINCT statement like this:

SELECT DISTINCT Publisher FROM Books;

The result is:

Publisher

دار العلم

Fast Press

Coriolis

 Now "Fast Press" is listed only once in the result-set.


Test your SQL Skills

To test your SQL skills click here.


previous next