Introduction

SQL (Structured Query Language) is a language used to manage relational databases. This language is designed to allow the user to store, retrieve, manage or manipulate data within a database management system (DBMS).
This article will talk about the commands that are an integral part of the SQL language, which is used to work with a “relational database management system” (DBMS) called “SQLite” (the current version of this DBMS is 3.0, i.e. sqllite3). In addition to this “Database Management System”, the commands can be applied with minor correction for other relational systems (MySql, PostgreSQL, Microsoft SQL Server…). The basic commands for working with SQL databases are very similar in all DBMSs, although each system has its own specifics (eg Microsoft SQL server is statically typed while SQLite is dynamically typed…). Read more about database management systems in the article “Database Management Systems (DBMS)”.
What is sqlite3?
sqlite3 is a frontend tool in Command Prompt or terminal for working with SQLite library. Using it, we can perform queries and display results independently of some other application. You can view the installation of this tool here.
Commands in sqlite3
In sqlite3, there are two types of commands: those that start with a period, so after them it is not necessary to signal to the SQL engine that the command ends, and those that do not start with a point, but must signal to the engine where the command ends with a semicolon. To exit sqlite3, it is necessary to use .quit or .exit or possibly “CTRL + C” in the terminal.
Creating and opening database
The command to create or open a database is the same. Whether the table will be created or just opened depends on whether it exists or not. If it does not exist then it will be created, and if there is such a database in the given folder then it will be opened. The syntax is as follows: first we write sqlite3 and then the database name together with the extension (.db):
|
1 |
sqlite3 DatabaseName.db |
After which the database will be created in the current directory and the Command Prompt will appear:
|
1 |
sqlite> |
Database verification is done with the command:
|
1 |
sqlite> .databases |
Basic commands for working with tables
Creating a table (CREATE TABLE)
The syntax for creating a table is as follows:
|
1 2 3 4 5 6 7 |
CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype ); |
By default, a column can contain NULL values (ie, some member can have no value in any of the columns). The constraint NOT NULL obliges the member NOT to accept that there is no value in a field, i.e. to have a NULL value. This requires the field to always contain a value, meaning you cannot insert a new member or update an old one without adding a value to the field that has “NOT NULL” defined.
Example
|
1 2 3 4 5 6 7 |
CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); |
In the previous example, ID, NAME, and AGE are required fields.
Listing all database tables (.tables)
Listing of all database tables is done with the command:
|
1 |
.tables. |
View table schema (.schema)
In order to see the scheme according to which the table was created, we use:
|
1 |
sqlite>.schema NAZIV_TABELE |
Deleting the table (DROP TABLE)
Deleting a certain table is done according to the following syntax:
|
1 |
DROP TABLE database_name.table_name; |
Inserting a table member (INSERT INTO)
Inserting a new member of the table means adding a new row not at the end of the table and is done with the command INSERT INTO.
There are two types of syntax:
- so-called “Detailed” syntax
- so-called “Simple” syntax
Detailed syntax:
|
1 2 |
INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)] VALUES (value1, value2, value3,...valueN); |
It is also necessary to specify the names of the columns of that table, and then insert new values.
Example
In the previous example, we created a table called COMPANY whose columns are (ID,NAME,AGE,ADDRESS,SALARY), so inserting each new member would look like this:
|
1 2 3 4 5 |
INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); |
Simple syntax
Simplified syntax implies that column names are not mentioned, but only values:
|
1 |
INSERT INTO COMPANY VALUES (7, 'James', 24, 'Houston', 10000.00 ); |
Update table member (UPDATE)
This query is used to modify an existing table row. The syntax looks like this:
|
1 2 3 |
UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition]; |
Example
The command in this example will change the company address to “Texas” within the “COMPANY” table member whose ID is 6
|
1 |
sqlite> UPDATE COMPANY SET ADDRESS = 'Texas' WHERE ID = 6; |
NOTE:
If you did not use the WHERE clause, then all the table members would have their address changed to “Texas”.
Deleting a table member (DELETE)
Deleting a specific table member/row is done with the syntax:
|
1 2 |
DELETE FROM table_name WHERE [condition]; |
Example
In this example, the table member whose ID is 6:
will be deleted
|
1 |
DELETE FROM COMPANY WHERE ID = 6; |
Getting data (query) from a table (SELECT)
The syntax of this command that selects data is as follows:
|
1 |
SELECT column1, column2, columnN FROM table_name; |
Example
|
1 |
sqlite> SELECT NAME, ID FROM COMPANY; |
So this expression returns only two columns:
|
1 2 3 4 5 6 7 8 |
NAME ID ---------- ---------- Paul 1 Allen 2 Teddy 3 Mark 4 David 5 Kim 6 |
NOTE:
The order of the columns within the command does not have to follow the order in the database!
Example
Often we want to display all the columns of a table and we can do that by specifying exactly all the column names:
|
1 |
sqlite> SELECT ID, NAME, AGE, ADDRESS, SALARY FROM COMPANY; |
However, we can do it in a simpler way using the wildcard * (star):
|
1 |
sqlite> SELECT * FROM COMPANY; |
Which returns the result:
|
1 2 3 4 5 6 7 8 |
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 |
WHERE clause
This clause is used to define a condition.
|
1 2 3 |
SELECT column1, column2, columnN FROM table_name WHERE [condition] |
Example
|
1 |
SELECT * FROM COMPANY WHERE AGE >= 25; |
This condition returns all rows where AGE is greater than or equal to 25:
|
1 2 3 4 5 6 |
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 |
LIMIT & OFFSET clause
LIMIT limits the number of rows that are selected, while OFFSET skips a certain number of rows. The syntax looks like this:
|
1 2 3 |
SELECT column1, column2, columnN FROM table_name LIMIT [no of rows] OFFSET [row num] |
Example
|
1 |
sqlite> SELECT * FROM COMPANY LIMIT 3; |
Returns the following:
|
1 2 3 4 5 |
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 |
And if we add an OFFSET that will skip these first three lines:
|
1 |
sqlite> SELECT * FROM COMPANY LIMIT 3 OFFSET 3; |
We get a continuation of the table:
|
1 2 3 4 5 |
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 |
ORDER BY clause
This clause is used to sort the members of a table in descending or ascending order. It is always placed at the end of the expression and the syntax looks like this:
|
1 2 3 |
SELECT column-list FROM table_name [ORDER BY column1, column2, .. columnN] [ASC | DESC]; |
Example
|
1 |
sqlite> SELECT * FROM COMPANY ORDER BY SALARY ASC; |
This expression returns all members of the table sorted in ascending order by the column SALARY:
|
1 2 3 4 5 6 7 8 |
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000.0 1 Paul 32 California 20000.0 3 Teddy 23 Norway 20000.0 6 Kim 22 South-Hall 45000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 |
AND operator
This operator makes it possible to use multiple conditions that need to be satisfied.
|
1 2 3 |
SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]...AND [conditionN]; |
Example
|
1 |
SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY > 25000; |
|
1 2 3 4 |
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 |
OR operator
This operator also makes it possible to compose a multiple condition, but it is enough that only one condition is satisfied.
|
1 2 3 |
SELECT column1, column2, columnN FROM table_name WHERE [condition1] OR [condition2]...OR [conditionN] |
Example
|
1 |
sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000; |
|
1 2 3 4 5 6 |
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 |
LIKE operator
The LIKE operator is used to find results where text values match the requested ones (not case sensitive). If the search text matches the pattern expression, the LIKE operator will return true. There are two wildcard characters used in conjunction with the LIKE operator:
- % (percentage) – represents zero, one or more characters
- _ (underscore) – represents only one character
Example
|
1 |
WHERE SALARY LIKE '200%' |
Returns results starting with 200 (2005, 20035, 200559…)
Example
|
1 |
WHERE SALARY LIKE '%200%' |
Returns results containing 200 (152005, 1420035…)
Example
|
1 |
WHERE SALARY LIKE '%2' |
Returns results that end with 2(152, 14205552…)
Example
|
1 |
WHERE SALARY LIKE '_2%3' |
Returns results where the second digit is 2 and the last digit is 3(123, 1205553…)
Example
|
1 |
WHERE SALARY LIKE '2_%_%' |
Returns results where the first digit is 2 and has at least two more digits.
Example
|
1 |
WHERE ADDRESS LIKE '%-%'; |
Returns results that have a middle line (South-Hall) in the text
GLOB operator
This operator is almost the same as the LIKE operator in that it is “case sensitive” and uses other wildcard labels even though they have the same meaning
- * (star) – represents zero, one or more characters (percent code LIKE)
- ? (question mark) – represents only one character (underscore code LIKE)
Example
|
1 |
WHERE SALARY GLOB '?2*3' |
Returns results where the second digit is 2 and the last digit is 3(123, 1205553…)
DISTINCT
This keyword with SELECT allows the output returned by the expression to have no “duplicates”. The syntax is like this:
|
1 2 |
SELECT DISTINCT column1, column2,.....columnN FROM table_name |
Example
|
1 |
sqlite> SELECT DISTINCT NAME, AGE FROM COMPANY; |
This expression returns the NAME and AGE columns but only with unique members in the NAME column:
|
1 2 3 4 5 6 7 8 |
NAME AGE ---------- ---------- Paul 32 Allen 25 Teddy 23 Mark 25 David 27 Kim 22 |
Export and output formatting
Unordered exit ie. the table view looks like this:
|
1 2 3 4 5 6 |
1|Paul|32|California|20000.0 2|Allen|25|Texas|15000.0 3|Teddy|23|Norway|20000.0 4|Mark|25|Rich-Mond |65000.0 5|David|27|Texas|85000.0 6|Kim|22|South-Hall|45000.0 |
However, there are certain commands that can improve this appearance and contribute to better readability.
.header (showing column names)
Showing the header with column names is enabled withcommand:
|
1 |
sqlite>.header on |
.mode (table layout)
The appearance of the displayed table depends on the selected mode:
- csv – Comma-separated values
- column − Left-aligned columns.
- html − HTML <table> code
- insert − SQL insert statements for TABLE
- line − One value per line
- list − Values delimited by .separator string
- tabs – Tab-separated values
- tcl – TCL list elements
The column mode is most often used because it is the most visible:
|
1 |
sqlite>.mode column |
.width (column width)
Sometimes it happens that the default column width (10 letters) is not enough, so we can predefine the width with the command .width.
|
1 |
sqlite>.width 10, 30, 20 |
After this the first three columns will have the passed widths.
Example
We have seen what the unsorted output of the table looks like from the previous examples, now we will improve it with the following commands:
|
1 2 3 4 |
sqlite> .header on sqlite> .mode column sqlite> .width 5 30 20 sqlite> SELECT * FROM COMPANY; |
Now the sorted output looks like this:
|
1 2 3 4 5 6 7 8 |
ID NAME AGE ADDRESS SALARY ----- ------------------------------ -------------------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 |
NOTE:
Once defined rules for output layout remain until we change the base.
Export to excel
To export the table to Excel, we first need to define the output type:
|
1 |
sqlite> .excel |
And then to hash what we want to include in that output:
|
1 |
sqlite> SELECT * FROM COMPANY; |
Installing sqlite3 tools
- Go to the download page “SQLite download page”, and choose to download where it says “Precompiled Binaries for …” next to the section where it says ” bundle of command-line tools for managing SQLite database files….”
- Create a new folder (eg named sqlite) and put the unzipped content from the downloaded folder (sqlite3.def, sqlite3.dll and sqlite3.exe) into it. After this, if we want, we can use sqlite3 in Command Prompt, but our path must point to this folder C:>sqlite.
-
To enable access to this tool from anywhere, we need to save the path to the newly created folder where we put the executable files in “Environment Variables”.
- Control Panel > System > Advanced System Settings > Environment Variables
- In the “User variables” box, look for whether the “Path” variable
- If it exists, then it is edited, and if not, it is necessary to create a new one with “New”
- The variable should be “Path” and the Value should be the path to the folder where the sqlite3 installation files were transferred (most often C:sqlite)
- Save on the OK button
already exists.
NOTE:
You need to restart “Command Prompt” (terminal) to see the changes!
In order to be sure that everything is OK, it is enough to write sqlite3 in the Command Prompt, after which we should get a response like this:
|
1 2 3 4 5 6 |
λ sqlite3 SQLite version 3.32.2 2020-06-04 12:58:43 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database. sqlite> . |
