To choose data from a database, use the SELECT statement.
The information that is returned is kept in a result table known as the result-set.
SELECT column1, column2, ...
FROM table_name;
The table you wish to pick data from has field names like column1, column2,… in this case. Use the following syntax to select every field in the table that is available:
SELECT * FROM table_name;
We’ll be using the well-known Northwind sample database in this tutorial.
A sample from the “Customers” table in the Northwind sample database is shown below:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 05021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 05023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
The following SQL statement selects the “CustomerName”, “City”, and “Country” columns from the “Customers” table:
SELECT CustomerName, City, Country FROM Customers;
The following SQL statement selects ALL the columns from the “Customers” table:
SELECT * FROM Customers;
To retrieve just distinct (different) data, use the SELECT DISTINCT command.
A column in a database may have a lot of duplicate entries, and there may be instances when you just want to list the unique values.
SELECT DISTINCT column1, column2, …
FROM table_name;
The “Country” column in the “Customers” table has all values (including duplicates) selected by the SQL query that follows:
SELECT Country FROM Customers;
Now, let us use the SELECT DISTINCT statement and see the result.
The following SQL statement selects only the DISTINCT values from the “Country” column in the “Customers” table:
SELECT DISTINCT Country FROM Customers;
The number of distinct (different) nations in the “Customers” table is counted and returned using the SQL statement that follows:
SELECT COUNT(DISTINCT Country) FROM Customers;
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.