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




SQLite functions

In this part of the SQLite tutorial, we will cover SQLite built-in functions. There are three types of

functions in SQLite database. Core, aggregate and date & time functions.


We will cover some functions from each group of SQLite functions.




Core functions

In this group we have various diverse functios. Some are numerical functions, some work with text.

Others do some very specific things.




  sqlite> SELECT sqlite_version() AS 'SQLite Version';




  SQLite Version




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




  3.5.9


The sqlite_version() function returns the version of the SQLite library.




  sqlite> SELECT random() AS Random;




  Random




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




  1056892254869386643
The random() function returns a pseudo-random integer between -9223372036854775808 and

+9223372036854775807.




  sqlite> SELECT max(cost) FROM Cars;




  max(cost)




  ----------




  350000




  sqlite> SELECT min(cost) FROM Cars;




  min(cost)




  ----------




  9000


In our example, the max() and min() functions return the most and the least expensive cars from the

Cars table.




  sqlite> SELECT upper(name) AS 'Names in Capitals' FROM Friends;




  Names in Capitals




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




  JANE
THOMAS




  FRANKLIN




  ELISABETH




  MARY




  LUCY




  JACK


The upper() function converts characters into upper-case letters.




  sqlite> SELECT length('ZetCode');




  length('ZetCode')




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




  7


The length() function returns the length of a string.




  sqlite> SELECT total_changes() AS 'Total changes';




  Total changes




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




  3
The total_changes() function returns the number of row changes caused by INSERT, UPDATE or

DELETE statements since the current database connection was opened. In the current database

connection, I have done three INSERT statements, so the total changes is equal to three.




Aggregate funcions

With aggregate functions, we get some statistical data.


Let's recap, what we have in the Cars table.




  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
Notice, that there are no duplicate records.




  sqlite> SELECT count(*) AS '# of cars' FROM Cars;




  # of cars




  ----------




  8


The count(*) function returns the number of rows in the table. In our table, we have eight cars.

Assuming, there are no duplicates.


In the Orders table, we have duplicate records of customers.




  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


Logically, each customer can make multiple orders. How do we count the number of orders and how do

we count the number of customers?




  sqlite> SELECT count(Customer) AS '# of orders'          FROM Orders;




  # of orders




  -----------




  11


This SQL statement returns the number of orders. To calculate the number of unique customers, we

have to utilize the DISTINCT keyword.




  sqlite> SELECT count(DISTINCT Customer) AS '# of customers' FROM Orders;




  # of customers




  --------------
5


We have 5 customers in our Orders table. They made 11 orders.


Next we are going to demonstrate the difference between the count(*) and count(ColumnName).

These function usages differ in the way, how they handle NULL values.




  sqlite> .nullvalue NULL


First, we change how sqlite3 shows NULL values. By default, the NULL value is shown as empty string.




  sqlite> CREATE TABLE IF NOT EXISTS Testing(id integer primary key);




  sqlite> DELETE FROM Testing;




  sqlite> INSERT INTO Testing VALUES(1);




  sqlite> INSERT INTO Testing VALUES(2);




  sqlite> INSERT INTO Testing VALUES(3);




  sqlite> INSERT INTO Testing VALUES(NULL);




  sqlite> INSERT INTO Testing VALUES(NULL);




  sqlite> SELECT * FROM Testing;




  id




  ----------




  1
2




  3




  NULL




  NULL


Here we create table Testing with 3 numerical and 2 NULL values.




  sqlite> SELECT count(*) AS '# of rows' FROM Testing;




  # of rows




  ----------




  5


The count(*) returns the number of rows in the table. It takes NULL values into account.




  sqlite> SELECT count(id) AS '# of non NULL values' FROM Testing;




  # of non NULL values




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




  3


The count(id) counts only non NULL values.




  sqlite> SELECT avg(cost) AS 'Average price' FROM Cars;
Average price




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




  88528.1666666667


The avg() function returns the average value of all non NULL records. In our example, we show the

average price of the car in the Cars table.


Finally, we mention the sum() function. It does a summation of all non NULL values.




  sqlite> SELECT sum(OrderPrice) AS Sum FROM Orders;




  Sum




  ----------




  4930


Here we count the sum of all orders made by our customers.




Date and time funcions

SQLite has functions for working with date and time. With these functions we can use various time

strings, modifiers and formats.




  sqlite> SELECT date('now');




  2009-11-05


The date() function with the now string return the current date.




  sqlite> SELECT datetime('now');
2009-11-05 20:01:07


The datetime() function returns the current date and time.




  sqlite> SELECT strftime('%d-%m-%Y');




  05-11-2009


We can use the the strftime() function to return a date in a different format.




  sqlite> SELECT "Current day " || strftime('%d');




  Current day 05


This SQL statement returns the current day of the month. We used the strftime() function.




  sqlite> SELECT 'Days to XMas:' || (strftime('%j', '2009-12-24') - strftime('%j',
  'now'));




  Days to XMas:49


Here we have computed the number of days till Christmas. The %j modifier gives the day of the year

for the time string.




  sqlite> SELECT date('now','start of year','10 months','weekday 4');




  2009-11-05


This SQL statement returns the first Thursday of the November for the current year. In this example, we

used three modifiers. start of year, +x months and weekday x. The now time string gives the

current date. The start of year shifts the date backwards to the beginning of the year. The 10

months adds 10 months to the current month (January). Finally, the weekday 4 modifier advances

the date forward to the first Thursday. We count from Sunday, 0.


In this part of the SQLite tutorial, we worked with the built-in SQLite functions.

Contenu connexe

Tendances

Oracle Web Adi For upload item master
Oracle Web Adi For upload item masterOracle Web Adi For upload item master
Oracle Web Adi For upload item masterAhmed Elshayeb
 
2 sql - single-row functions
2   sql - single-row functions2   sql - single-row functions
2 sql - single-row functionsAnkit Dubey
 
sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)Ankit Dubey
 
Oracle dbms_xplan.display_cursor format
Oracle dbms_xplan.display_cursor formatOracle dbms_xplan.display_cursor format
Oracle dbms_xplan.display_cursor formatFranck Pachot
 
Les01[1]Writing Basic SQL Statements
Les01[1]Writing Basic SQL StatementsLes01[1]Writing Basic SQL Statements
Les01[1]Writing Basic SQL Statementssiavosh kaviani
 
Optimizer in oracle 11g by wwf from ebay COC
Optimizer in oracle 11g by wwf from ebay COCOptimizer in oracle 11g by wwf from ebay COC
Optimizer in oracle 11g by wwf from ebay COCLouis liu
 
SQL WORKSHOP::Lecture 12
SQL WORKSHOP::Lecture 12SQL WORKSHOP::Lecture 12
SQL WORKSHOP::Lecture 12Umair Amjad
 
MySQL partitions tutorial
MySQL partitions tutorialMySQL partitions tutorial
MySQL partitions tutorialGiuseppe Maxia
 
Database Management System
Database Management SystemDatabase Management System
Database Management SystemHitesh Mohapatra
 

Tendances (20)

Les10
Les10Les10
Les10
 
4sem dbms(1)
4sem dbms(1)4sem dbms(1)
4sem dbms(1)
 
Les09 Manipulating Data
Les09 Manipulating DataLes09 Manipulating Data
Les09 Manipulating Data
 
Les06 Subqueries
Les06 SubqueriesLes06 Subqueries
Les06 Subqueries
 
Les02
Les02Les02
Les02
 
Les12
Les12Les12
Les12
 
Les04 Displaying Data From Multiple Table
Les04 Displaying Data From Multiple TableLes04 Displaying Data From Multiple Table
Les04 Displaying Data From Multiple Table
 
Les05 Aggregating Data Using Group Function
Les05 Aggregating Data Using Group FunctionLes05 Aggregating Data Using Group Function
Les05 Aggregating Data Using Group Function
 
Les02 Restricting And Sorting Data
Les02 Restricting And Sorting DataLes02 Restricting And Sorting Data
Les02 Restricting And Sorting Data
 
Oracle Web Adi For upload item master
Oracle Web Adi For upload item masterOracle Web Adi For upload item master
Oracle Web Adi For upload item master
 
Les12[1]Creating Views
Les12[1]Creating ViewsLes12[1]Creating Views
Les12[1]Creating Views
 
Les06[1]Subqueries
Les06[1]SubqueriesLes06[1]Subqueries
Les06[1]Subqueries
 
2 sql - single-row functions
2   sql - single-row functions2   sql - single-row functions
2 sql - single-row functions
 
sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)
 
Oracle dbms_xplan.display_cursor format
Oracle dbms_xplan.display_cursor formatOracle dbms_xplan.display_cursor format
Oracle dbms_xplan.display_cursor format
 
Les01[1]Writing Basic SQL Statements
Les01[1]Writing Basic SQL StatementsLes01[1]Writing Basic SQL Statements
Les01[1]Writing Basic SQL Statements
 
Optimizer in oracle 11g by wwf from ebay COC
Optimizer in oracle 11g by wwf from ebay COCOptimizer in oracle 11g by wwf from ebay COC
Optimizer in oracle 11g by wwf from ebay COC
 
SQL WORKSHOP::Lecture 12
SQL WORKSHOP::Lecture 12SQL WORKSHOP::Lecture 12
SQL WORKSHOP::Lecture 12
 
MySQL partitions tutorial
MySQL partitions tutorialMySQL partitions tutorial
MySQL partitions tutorial
 
Database Management System
Database Management SystemDatabase Management System
Database Management System
 

En vedette

Introduction to sq lite
Introduction to sq liteIntroduction to sq lite
Introduction to sq litepunu_82
 
第5回SCDN - Things that become possible with HTML5
第5回SCDN - Things that become possible with HTML5第5回SCDN - Things that become possible with HTML5
第5回SCDN - Things that become possible with HTML5scdn
 
Java one 2010
Java one 2010Java one 2010
Java one 2010scdn
 
Creating, altering and dropping tables
Creating, altering and dropping tablesCreating, altering and dropping tables
Creating, altering and dropping tablespunu_82
 
SCDN 1
SCDN 1SCDN 1
SCDN 1scdn
 

En vedette (6)

Introduction to sq lite
Introduction to sq liteIntroduction to sq lite
Introduction to sq lite
 
мясной дом Бородина.
мясной дом Бородина.мясной дом Бородина.
мясной дом Бородина.
 
第5回SCDN - Things that become possible with HTML5
第5回SCDN - Things that become possible with HTML5第5回SCDN - Things that become possible with HTML5
第5回SCDN - Things that become possible with HTML5
 
Java one 2010
Java one 2010Java one 2010
Java one 2010
 
Creating, altering and dropping tables
Creating, altering and dropping tablesCreating, altering and dropping tables
Creating, altering and dropping tables
 
SCDN 1
SCDN 1SCDN 1
SCDN 1
 

Similaire à SQLite Functions Guide

Sq lite expressions
Sq lite expressionsSq lite expressions
Sq lite expressionspunu_82
 
The select statement
The select statementThe select statement
The select statementpunu_82
 
SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?Andrej Pashchenko
 
OpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developersOpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developersConnor McDonald
 
Database management system file
Database management system fileDatabase management system file
Database management system fileAnkit Dixit
 
Sq lite python tutorial sqlite programming in python
Sq lite python tutorial   sqlite programming in pythonSq lite python tutorial   sqlite programming in python
Sq lite python tutorial sqlite programming in pythonMartin Soria
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sqlMcNamaraChiwaye
 
Latin America Tour 2019 - 10 great sql features
Latin America Tour 2019  - 10 great sql featuresLatin America Tour 2019  - 10 great sql features
Latin America Tour 2019 - 10 great sql featuresConnor McDonald
 
Sql interview questions
Sql interview questionsSql interview questions
Sql interview questionsnagesh Rao
 
Les09[1]Manipulating Data
Les09[1]Manipulating DataLes09[1]Manipulating Data
Les09[1]Manipulating Datasiavosh kaviani
 
Les07[1]Multiple-Column Subqueries
Les07[1]Multiple-Column SubqueriesLes07[1]Multiple-Column Subqueries
Les07[1]Multiple-Column Subqueriessiavosh kaviani
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesKeshav Murthy
 
12c SQL Plan Directives
12c SQL Plan Directives12c SQL Plan Directives
12c SQL Plan DirectivesFranck Pachot
 

Similaire à SQLite Functions Guide (20)

Sq lite expressions
Sq lite expressionsSq lite expressions
Sq lite expressions
 
The select statement
The select statementThe select statement
The select statement
 
Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
 
SQL (1).pptx
SQL (1).pptxSQL (1).pptx
SQL (1).pptx
 
SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?SQL Macros - Game Changing Feature for SQL Developers?
SQL Macros - Game Changing Feature for SQL Developers?
 
Les01
Les01Les01
Les01
 
OpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developersOpenWorld Sep14 12c for_developers
OpenWorld Sep14 12c for_developers
 
Database management system file
Database management system fileDatabase management system file
Database management system file
 
Sq lite python tutorial sqlite programming in python
Sq lite python tutorial   sqlite programming in pythonSq lite python tutorial   sqlite programming in python
Sq lite python tutorial sqlite programming in python
 
The ultimate-guide-to-sql
The ultimate-guide-to-sqlThe ultimate-guide-to-sql
The ultimate-guide-to-sql
 
ORACLE NOTES
ORACLE NOTESORACLE NOTES
ORACLE NOTES
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Beg sql
Beg sqlBeg sql
Beg sql
 
Latin America Tour 2019 - 10 great sql features
Latin America Tour 2019  - 10 great sql featuresLatin America Tour 2019  - 10 great sql features
Latin America Tour 2019 - 10 great sql features
 
Sql interview questions
Sql interview questionsSql interview questions
Sql interview questions
 
Les09[1]Manipulating Data
Les09[1]Manipulating DataLes09[1]Manipulating Data
Les09[1]Manipulating Data
 
5 Cool Things About SQL
5 Cool Things About SQL5 Cool Things About SQL
5 Cool Things About SQL
 
Les07[1]Multiple-Column Subqueries
Les07[1]Multiple-Column SubqueriesLes07[1]Multiple-Column Subqueries
Les07[1]Multiple-Column Subqueries
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql Features
 
12c SQL Plan Directives
12c SQL Plan Directives12c SQL Plan Directives
12c SQL Plan Directives
 

Dernier

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Dernier (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

SQLite Functions Guide

  • 1. Home Contents SQLite functions In this part of the SQLite tutorial, we will cover SQLite built-in functions. There are three types of functions in SQLite database. Core, aggregate and date & time functions. We will cover some functions from each group of SQLite functions. Core functions In this group we have various diverse functios. Some are numerical functions, some work with text. Others do some very specific things. sqlite> SELECT sqlite_version() AS 'SQLite Version'; SQLite Version -------------- 3.5.9 The sqlite_version() function returns the version of the SQLite library. sqlite> SELECT random() AS Random; Random ------------------- 1056892254869386643
  • 2. The random() function returns a pseudo-random integer between -9223372036854775808 and +9223372036854775807. sqlite> SELECT max(cost) FROM Cars; max(cost) ---------- 350000 sqlite> SELECT min(cost) FROM Cars; min(cost) ---------- 9000 In our example, the max() and min() functions return the most and the least expensive cars from the Cars table. sqlite> SELECT upper(name) AS 'Names in Capitals' FROM Friends; Names in Capitals ----------------- JANE
  • 3. THOMAS FRANKLIN ELISABETH MARY LUCY JACK The upper() function converts characters into upper-case letters. sqlite> SELECT length('ZetCode'); length('ZetCode') ----------------- 7 The length() function returns the length of a string. sqlite> SELECT total_changes() AS 'Total changes'; Total changes ------------- 3
  • 4. The total_changes() function returns the number of row changes caused by INSERT, UPDATE or DELETE statements since the current database connection was opened. In the current database connection, I have done three INSERT statements, so the total changes is equal to three. Aggregate funcions With aggregate functions, we get some statistical data. Let's recap, what we have in the Cars table. 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
  • 5. Notice, that there are no duplicate records. sqlite> SELECT count(*) AS '# of cars' FROM Cars; # of cars ---------- 8 The count(*) function returns the number of rows in the table. In our table, we have eight cars. Assuming, there are no duplicates. In the Orders table, we have duplicate records of customers. sqlite> SELECT * FROM Orders; Id OrderPrice Customer ---------- ---------- ---------- 1 1200 Williamson 2 200 Robertson 3 40 Robertson 4 1640 Smith 5 100 Robertson
  • 6. 6 50 Williamson 7 150 Smith 8 250 Smith 9 840 Brown 10 440 Black 11 20 Brown Logically, each customer can make multiple orders. How do we count the number of orders and how do we count the number of customers? sqlite> SELECT count(Customer) AS '# of orders' FROM Orders; # of orders ----------- 11 This SQL statement returns the number of orders. To calculate the number of unique customers, we have to utilize the DISTINCT keyword. sqlite> SELECT count(DISTINCT Customer) AS '# of customers' FROM Orders; # of customers --------------
  • 7. 5 We have 5 customers in our Orders table. They made 11 orders. Next we are going to demonstrate the difference between the count(*) and count(ColumnName). These function usages differ in the way, how they handle NULL values. sqlite> .nullvalue NULL First, we change how sqlite3 shows NULL values. By default, the NULL value is shown as empty string. sqlite> CREATE TABLE IF NOT EXISTS Testing(id integer primary key); sqlite> DELETE FROM Testing; sqlite> INSERT INTO Testing VALUES(1); sqlite> INSERT INTO Testing VALUES(2); sqlite> INSERT INTO Testing VALUES(3); sqlite> INSERT INTO Testing VALUES(NULL); sqlite> INSERT INTO Testing VALUES(NULL); sqlite> SELECT * FROM Testing; id ---------- 1
  • 8. 2 3 NULL NULL Here we create table Testing with 3 numerical and 2 NULL values. sqlite> SELECT count(*) AS '# of rows' FROM Testing; # of rows ---------- 5 The count(*) returns the number of rows in the table. It takes NULL values into account. sqlite> SELECT count(id) AS '# of non NULL values' FROM Testing; # of non NULL values -------------------- 3 The count(id) counts only non NULL values. sqlite> SELECT avg(cost) AS 'Average price' FROM Cars;
  • 9. Average price ---------------- 88528.1666666667 The avg() function returns the average value of all non NULL records. In our example, we show the average price of the car in the Cars table. Finally, we mention the sum() function. It does a summation of all non NULL values. sqlite> SELECT sum(OrderPrice) AS Sum FROM Orders; Sum ---------- 4930 Here we count the sum of all orders made by our customers. Date and time funcions SQLite has functions for working with date and time. With these functions we can use various time strings, modifiers and formats. sqlite> SELECT date('now'); 2009-11-05 The date() function with the now string return the current date. sqlite> SELECT datetime('now');
  • 10. 2009-11-05 20:01:07 The datetime() function returns the current date and time. sqlite> SELECT strftime('%d-%m-%Y'); 05-11-2009 We can use the the strftime() function to return a date in a different format. sqlite> SELECT "Current day " || strftime('%d'); Current day 05 This SQL statement returns the current day of the month. We used the strftime() function. sqlite> SELECT 'Days to XMas:' || (strftime('%j', '2009-12-24') - strftime('%j', 'now')); Days to XMas:49 Here we have computed the number of days till Christmas. The %j modifier gives the day of the year for the time string. sqlite> SELECT date('now','start of year','10 months','weekday 4'); 2009-11-05 This SQL statement returns the first Thursday of the November for the current year. In this example, we used three modifiers. start of year, +x months and weekday x. The now time string gives the current date. The start of year shifts the date backwards to the beginning of the year. The 10 months adds 10 months to the current month (January). Finally, the weekday 4 modifier advances the date forward to the first Thursday. We count from Sunday, 0. In this part of the SQLite tutorial, we worked with the built-in SQLite functions.