SlideShare une entreprise Scribd logo
1  sur  11
Télécharger pour lire hors ligne
Home Contents




The SELECT statement

This part of the SQLite tutorial will be covering the SELECT statement understood by the SQLite in

detail.




Retrieving all data

The following SQL statement is one of the most common ones. It is also one of the most expensive

ones.




  sqlite> SELECT * FROM Cars;




  Id            Name           Cost




  ----------    ----------     ----------




  1             Audi           52642




  2             Mercedes       57127




  3             Skoda          9000




  4             Volvo          29000




  5             Bentley        350000




  6             Citroen        21000
7              Hummer         41400




  8              Volkswagen     21600


Here we retrieve all data from the Cars table.




Selecting specific columns

We can use the SELECT statement to retrieve specific columns. The column names follow the SELECT

word.




  sqlite> SELECT Name, Cost FROM Cars;




  Name           Cost




  ----------     ----------




  Audi           52642




  Mercedes       57127




  Skoda          9000




  Volvo          29000




  Bentley        350000




  Citroen        21000




  Hummer         41400
Volkswagen    21600


We retrieve the name and the cost columns. The column names are separated by commas.




Renaming column names

We can rename the column names of the returned result set. For this, we use the AS clause.




  sqlite> SELECT Name, Cost AS Price FROM Cars;




  Name          Price




  ----------    ----------




  Audi          52642




  Mercedes      57127




  Skoda         9000




  Volvo         29000




  Bentley       350000




  Citroen       21000




  Hummer        41400




  Volkswagen    21600


Say we wanted to name the column price rather than cost. With the above SQL statement, we have
accomplished this.




Limiting data output

As we mentioned above, retrieving all data is expensive when dealing with large amounts of data. We

can use the LIMIT clause to limit the data amount returned by the statement.




  sqlite> SELECT * FROM Cars LIMIT 4;




  Id            Name           Cost




  ----------    ----------     ----------




  1             Audi           52642




  2             Mercedes       57127




  3             Skoda          9000




  4             Volvo          29000


The LIMIT clause limits the number of rows returned to 4.


The OFFSET clause following LIMIT specifies how many rows to skip at the beginning of the result set.




  sqlite> SELECT * FROM Cars LIMIT 4 OFFSET 2;




  Id            Name           Cost




  ----------    ----------     ----------
3              Skoda        9000




  4              Volvo        29000




  5              Bentley      350000




  6              Citroen      21000


Here we select all data from max four rows, and we begin with the third row. The OFFSET clause skips

the first two rows.




Orderig data

We use the ORDER BY clause to sort the returned data set. The ORDER BY clause is followed by the

column on which we do the sorting. The ASC keyword sorts the data in ascending order, the DESC in

descending order.




  sqlite> SELECT Name, Cost FROM Cars ORDER BY Cost DESC;




  Name           Cost




  ----------     ----------




  Bentley        350000




  Mercedes       57127




  Audi           52642




  Hummer         41400
Volvo         29000




  Volkswagen    21600




  Citroen       21000




  Skoda         9000


In the above SQL statement, we select name, cost columns from the Cars table and sort it by the cost

of the cars in descending order. So the most expensive cars come first.




Selecting specific rows with the WHERE Clause

In the following examples, we are going to use the Orders table.




  sqlite> SELECT * FROM Orders;




  Id            OrderPrice     Customer




  ----------    ----------     ----------




  1             1200           Williamson




  2             200            Robertson




  3             40             Robertson




  4             1640           Smith




  5             100            Robertson
6              50             Williamson




  7              150            Smith




  8              250            Smith




  9              840            Brown




  10             440            Black




  11             20             Brown


Here we see all the data from the Orders table.


Next, we want to select a specific row.




  sqlite> SELECT * FROM Orders WHERE id=6;




  Id             OrderPrice     Customer




  ----------     ----------     ----------




  6              50             Williamson


The above SQL statement selects a row which has id 6.




  sqlite> SELECT * FROM Orders WHERE Customer="Smith";




  Id             OrderPrice     Customer




  ----------     ----------     ----------
4              1640          Smith




  7              150           Smith




  8              250           Smith


The above SQL statement selects all orders from the Smith customer.


We can use the LIKE keyword to look for a specific pattern in the data.




  sqlite> SELECT * FROM Orders WHERE Customer LIKE 'B%';




  Id             OrderPrice    Customer




  ----------     ----------    ----------




  9              840           Brown




  10             440           Black




  11             20            Brown


This SQL statemet selects all orders from customers whose names begin with B character.




Removing duplicate items

The DISTINCT keyword is used to select only unique items from the result set.




  sqlite> SELECT Customer FROM Orders Where Customer LIKE 'B%';




  Customer
----------




  Brown




  Black




  Brown


This time we have selected customers whose names begin with B character. We can see, that Brown is

mentioned twice. To remove duplicates, we use the DISTINCT keyword.




  sqlite> SELECT DISTINCT Customer FROM Orders Where Customer LIKE 'B%';




  Customer




  ----------




  Black




  Brown


This is the correct solution.




Grouping data

The GROUP BY clause is used to combine database records with identical values into a single record. It

is often used with the aggregation functions.


Say we wanted to find out, the sum of each customers' orders.




  sqlite> SELECT sum(OrderPrice) AS Total, Customer FROM Orders GROUP BY Customer;
Total         Customer




  ----------    ----------




  440           Black




  860           Brown




  340           Robertson




  2040          Smith




  1250          Williamson


We used the sum() keyword returns the total sum of a numeric column. The GROUP BY clause divides

the total sum among the customers. So we can see, that Black has ordered items for 440 or Smith for

2040.


We cannot use the WHERE clause when aggregate functions were used. We use the HAVING clause.




  sqlite> SELECT sum(OrderPrice) AS Total, Customer FROM Orders




           GROUP BY Customer HAVING sum(OrderPrice)>1000;




  Total         Customer




  ----------    ----------




  2040          Smith




  1250          Williamson
The above SQL statement selects customers whose total orders where greater than 1000 units.


In this part of the SQLite tutorial, we mentioned the SQL SELECT statement in more detail.

Contenu connexe

Similaire à The select statement

Sq lite functions
Sq lite functionsSq lite functions
Sq lite functions
punu_82
 
The sqlite3 commnad line tool
The sqlite3 commnad line toolThe sqlite3 commnad line tool
The sqlite3 commnad line tool
punu_82
 
Les01-Oracle
Les01-OracleLes01-Oracle
Les01-Oracle
suman1248
 
Les08-Oracle
Les08-OracleLes08-Oracle
Les08-Oracle
suman1248
 
Sq lite expressions
Sq lite expressionsSq lite expressions
Sq lite expressions
punu_82
 
May Woo Bi Portfolio
May Woo Bi PortfolioMay Woo Bi Portfolio
May Woo Bi Portfolio
maywoo
 

Similaire à The select statement (20)

Sq lite functions
Sq lite functionsSq lite functions
Sq lite functions
 
The sqlite3 commnad line tool
The sqlite3 commnad line toolThe sqlite3 commnad line tool
The sqlite3 commnad line tool
 
Les01
Les01Les01
Les01
 
Les01
Les01Les01
Les01
 
Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
 
Les01 Writing Basic Sql Statements
Les01 Writing Basic Sql StatementsLes01 Writing Basic Sql Statements
Les01 Writing Basic Sql Statements
 
Les01-Oracle
Les01-OracleLes01-Oracle
Les01-Oracle
 
Les08-Oracle
Les08-OracleLes08-Oracle
Les08-Oracle
 
ORACLE NOTES
ORACLE NOTESORACLE NOTES
ORACLE NOTES
 
Sq lite expressions
Sq lite expressionsSq lite expressions
Sq lite expressions
 
SQL (1).pptx
SQL (1).pptxSQL (1).pptx
SQL (1).pptx
 
Les04 Displaying Data From Multiple Table
Les04 Displaying Data From Multiple TableLes04 Displaying Data From Multiple Table
Les04 Displaying Data From Multiple Table
 
Les02 Restricting And Sorting Data
Les02 Restricting And Sorting DataLes02 Restricting And Sorting Data
Les02 Restricting And Sorting Data
 
May Woo Bi Portfolio
May Woo Bi PortfolioMay Woo Bi Portfolio
May Woo Bi Portfolio
 
Sangam 19 - Analytic SQL
Sangam 19 - Analytic SQLSangam 19 - Analytic SQL
Sangam 19 - Analytic SQL
 
Beginers guide for oracle sql
Beginers guide for oracle sqlBeginers guide for oracle sql
Beginers guide for oracle sql
 
Les12[1]Creating Views
Les12[1]Creating ViewsLes12[1]Creating Views
Les12[1]Creating Views
 
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكل
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكلحل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكل
حل اسئلة الكتاب السعودى فى شرح قواعد البيانات اوراكل
 
Analytic SQL Sep 2013
Analytic SQL Sep 2013Analytic SQL Sep 2013
Analytic SQL Sep 2013
 
Les05 Aggregating Data Using Group Function
Les05 Aggregating Data Using Group FunctionLes05 Aggregating Data Using Group Function
Les05 Aggregating Data Using Group Function
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Dernier (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

The select statement

  • 1. Home Contents The SELECT statement This part of the SQLite tutorial will be covering the SELECT statement understood by the SQLite in detail. Retrieving all data The following SQL statement is one of the most common ones. It is also one of the most expensive ones. sqlite> SELECT * FROM Cars; Id Name Cost ---------- ---------- ---------- 1 Audi 52642 2 Mercedes 57127 3 Skoda 9000 4 Volvo 29000 5 Bentley 350000 6 Citroen 21000
  • 2. 7 Hummer 41400 8 Volkswagen 21600 Here we retrieve all data from the Cars table. Selecting specific columns We can use the SELECT statement to retrieve specific columns. The column names follow the SELECT word. sqlite> SELECT Name, Cost FROM Cars; Name Cost ---------- ---------- Audi 52642 Mercedes 57127 Skoda 9000 Volvo 29000 Bentley 350000 Citroen 21000 Hummer 41400
  • 3. Volkswagen 21600 We retrieve the name and the cost columns. The column names are separated by commas. Renaming column names We can rename the column names of the returned result set. For this, we use the AS clause. sqlite> SELECT Name, Cost AS Price FROM Cars; Name Price ---------- ---------- Audi 52642 Mercedes 57127 Skoda 9000 Volvo 29000 Bentley 350000 Citroen 21000 Hummer 41400 Volkswagen 21600 Say we wanted to name the column price rather than cost. With the above SQL statement, we have
  • 4. accomplished this. Limiting data output As we mentioned above, retrieving all data is expensive when dealing with large amounts of data. We can use the LIMIT clause to limit the data amount returned by the statement. sqlite> SELECT * FROM Cars LIMIT 4; Id Name Cost ---------- ---------- ---------- 1 Audi 52642 2 Mercedes 57127 3 Skoda 9000 4 Volvo 29000 The LIMIT clause limits the number of rows returned to 4. The OFFSET clause following LIMIT specifies how many rows to skip at the beginning of the result set. sqlite> SELECT * FROM Cars LIMIT 4 OFFSET 2; Id Name Cost ---------- ---------- ----------
  • 5. 3 Skoda 9000 4 Volvo 29000 5 Bentley 350000 6 Citroen 21000 Here we select all data from max four rows, and we begin with the third row. The OFFSET clause skips the first two rows. Orderig data We use the ORDER BY clause to sort the returned data set. The ORDER BY clause is followed by the column on which we do the sorting. The ASC keyword sorts the data in ascending order, the DESC in descending order. sqlite> SELECT Name, Cost FROM Cars ORDER BY Cost DESC; Name Cost ---------- ---------- Bentley 350000 Mercedes 57127 Audi 52642 Hummer 41400
  • 6. Volvo 29000 Volkswagen 21600 Citroen 21000 Skoda 9000 In the above SQL statement, we select name, cost columns from the Cars table and sort it by the cost of the cars in descending order. So the most expensive cars come first. Selecting specific rows with the WHERE Clause In the following examples, we are going to use the Orders table. sqlite> SELECT * FROM Orders; Id OrderPrice Customer ---------- ---------- ---------- 1 1200 Williamson 2 200 Robertson 3 40 Robertson 4 1640 Smith 5 100 Robertson
  • 7. 6 50 Williamson 7 150 Smith 8 250 Smith 9 840 Brown 10 440 Black 11 20 Brown Here we see all the data from the Orders table. Next, we want to select a specific row. sqlite> SELECT * FROM Orders WHERE id=6; Id OrderPrice Customer ---------- ---------- ---------- 6 50 Williamson The above SQL statement selects a row which has id 6. sqlite> SELECT * FROM Orders WHERE Customer="Smith"; Id OrderPrice Customer ---------- ---------- ----------
  • 8. 4 1640 Smith 7 150 Smith 8 250 Smith The above SQL statement selects all orders from the Smith customer. We can use the LIKE keyword to look for a specific pattern in the data. sqlite> SELECT * FROM Orders WHERE Customer LIKE 'B%'; Id OrderPrice Customer ---------- ---------- ---------- 9 840 Brown 10 440 Black 11 20 Brown This SQL statemet selects all orders from customers whose names begin with B character. Removing duplicate items The DISTINCT keyword is used to select only unique items from the result set. sqlite> SELECT Customer FROM Orders Where Customer LIKE 'B%'; Customer
  • 9. ---------- Brown Black Brown This time we have selected customers whose names begin with B character. We can see, that Brown is mentioned twice. To remove duplicates, we use the DISTINCT keyword. sqlite> SELECT DISTINCT Customer FROM Orders Where Customer LIKE 'B%'; Customer ---------- Black Brown This is the correct solution. Grouping data The GROUP BY clause is used to combine database records with identical values into a single record. It is often used with the aggregation functions. Say we wanted to find out, the sum of each customers' orders. sqlite> SELECT sum(OrderPrice) AS Total, Customer FROM Orders GROUP BY Customer;
  • 10. Total Customer ---------- ---------- 440 Black 860 Brown 340 Robertson 2040 Smith 1250 Williamson We used the sum() keyword returns the total sum of a numeric column. The GROUP BY clause divides the total sum among the customers. So we can see, that Black has ordered items for 440 or Smith for 2040. We cannot use the WHERE clause when aggregate functions were used. We use the HAVING clause. sqlite> SELECT sum(OrderPrice) AS Total, Customer FROM Orders GROUP BY Customer HAVING sum(OrderPrice)>1000; Total Customer ---------- ---------- 2040 Smith 1250 Williamson
  • 11. The above SQL statement selects customers whose total orders where greater than 1000 units. In this part of the SQLite tutorial, we mentioned the SQL SELECT statement in more detail.