SQL Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Introduction to SQL

SQL is a standard language for storing, manipulating and retrieving data in databases.
Tool: SQLite
SQLite is an open-source, zero-configuration, self-contained, stand-alone, transaction relational
database engine designed to be embedded into an application.
DML COMMANDS

DML (Data Manipulation Language) commands are the most frequently used SQL commands and
is used to query and manipulate the existing database objects. Some of the commands are Insert,
Select, Update, Delete.
In order to run DML commands, we will use sample database chinook.db.
First, use the command line program and navigate to the SQLite directory where the sqlite3.exe
file is located:
c:\sqlite>

Second, use the following command to connect to the chinook sample database located in
the sqlite folder.

c:\sqlite>sqlite3 c:\sqlite\chinook.db
You should see the following command:
sqlite>

1. Simple query:
SQLite Select:
SQLite SELECT statement is used to fetch the data from an SQLite database table which returns
data in the form of a result table.

Syntax
Following is the basic syntax of SQLite SELECT statement.
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2 ... are the fields of a table, whose values you want to fetch. If you want
to fetch all the fields available in the field, then you can use the following syntax −
SELECT * FROM table_name;
Apply the following query:

sqlite>SELECT
trackid,
name,
composer,
unitprice
FROM
tracks;

Change the format of output as follows and run above query again.

sqlite>.header on
sqlite>.mode column

You specify a list column names, which you want to get data, in the SELECT clause and
the tracks table in the FROM clause. SQLite returns the following result:

Task:
Display records of employee id, last name, first name of employees table.

Setting Output Column Width


Sometimes, you will face a problem related to the truncated output in case of .mode
column which happens because of default width of the column to be displayed. What you can
do is, you can set column displayable column width using .width num, num.... command as
follows −
sqlite>.width 10, 20, 10

2. Sorting rows
ORDER BY:

SQLite stores rows in a table in an unspecified order. It means that the rows in the table may or
may not be in the order that they were inserted.

If you use the SELECT statement to query data from a table, the order of rows in the result set is
unspecified. To sort the result set, you add the ORDER BY clause in the SELECT statement as
follows:

SELECT
select_list
FROM
table
ORDER BY
column_1 ASC,
column_2 DESC;

• The ASC keyword means ascending.


• And DESC keyword means descending.

If you don’t specify the ASC or DESC keyword, SQLite sorts the result set using the ASC option.
In other words, it sorts the result set in the ascending order by default.
In case you want to sort the result set by multiple columns, you use a comma (,) to separate
columns. The ORDER BY clause sorts rows using columns or expressions from left to right. In
other words, the ORDER BY clause sorts the rows using the first column in the list. Then, it sorts
the sorted rows using the second column, and so on.

SELECT
name,
milliseconds,
albumid
FROM
tracks
ORDER BY
albumid ASC;
Task: To sort the sorted result (by AlbumId) above by the Milliseconds column in descending or
der.

3. Filtering data

SELECT DISTINT:

The DISTINCT clause is an optional clause of the SELECT statement. The DISTINCT clause allows
you to remove the duplicate rows in the result set.

The following statement illustrates the syntax of the DISTINCT clause:

SELECT DISTINCT select_list


FROM table;

In this syntax:

• First, the DISTINCT clause must appear immediately after the SELECT keyword.
• Second, you place a column or a list of columns after the DISTINCT keyword. If you use one
column, SQLite uses values in that column to evaluate the duplicate. In case you use
multiple columns, SQLite uses the combination of values in these columns to evaluate the
duplicate.
Suppose you want to know the cities where the customers locate, you can use
the SELECT statement to get data from the city column of the customers table as follows:

SELECT city
FROM customers
ORDER BY city;

It returns 59 rows. There are few duplicate rows such as Berlin London, and Mountain View To
remove these duplicate rows, you use the DISTINCT clause as follows:

SELECT DISTINCT city


FROM customers;
Task: To remove duplicate the city and country from customer table.
WHERE:

The WHERE clause is an optional clause of the SELECT statement. It appears after
the FROM clause as the following statement:

SELECT
column_list
FROM
table
WHERE
search_condition;

You add a WHERE clause to the SELECT statement to filter data returned by the query.
The WHERE clause is also known as a set of conditions or a predicate list.

When evaluating a SELECT statement with a WHERE clause, SQLite uses the following steps:

1. First, check the table in the FROM clause.


2. Second, evaluate the conditions in the WHERE clause to get the rows that met the
conditions.
3. Third, make the final result set based on the rows in the previous step with columns in
the SELECT clause.

SQLite comparison operators

Operator Meaning
= Equal to
<> or != Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to

SQLite logical operators

Logical operators allow you to test the truth of some expressions. A logical operator returns 1, 0,
or a NULL value.
Notice that SQLite does not provide Boolean data type therefore 1 means TRUE, and 0 means
FALSE.

The following table illustrates the SQLite logical operators:

Operator Meaning

ALL returns 1 if all expressions are 1.

AND The AND operator allows the existence of multiple conditions in an SQL statement's
WHERE clause.

ANY returns 1 if any one of a set of comparisons is 1.

BETWEEN The BETWEEN operator is used to search for values that are within a set of values,
given the minimum value and the maximum value.

EXISTS The EXISTS operator is used to search for the presence of a row in a specified table
that meets certain criteria.

IN The IN operator is used to compare a value to a list of literal values that have been
specified.

LIKE The LIKE operator is used to compare a value to similar values using wildcard operators.

NOT reverses the value of other operators such as NOT EXISTS, NOT IN, NOT BETWEEN, etc.

OR The OR operator is used to combine multiple conditions in an SQL statement's


WHERE clause.

SELECT
name,
milliseconds,
bytes,
albumid
FROM
tracks
WHERE
albumid = 1;
SELECT
name,
milliseconds,
bytes,
albumid
FROM
tracks
WHERE
albumid = 1
AND milliseconds > 250000;

Like:
Sometimes, you don’t know exactly the complete keyword that you want to query. For example,
you may know that your most favorite song contains the word, elevator but you don’t know
exactly the name.
To query data based on partial information, you use the LIKE operator in the WHERE clause of
the SELECT statement as follows:

SELECT
column_list
FROM
table_name
WHERE
column_1 LIKE pattern;
The percent sign % wildcard examples
The s% pattern that uses the percent sign wildcard ( %) matches any string that starts
with s e.g.,son and so.
The %er pattern matches any string that ends with er like peter, clever, etc.
And the %per% pattern matches any string that contains per such as percent and peeper.
The underscore _ wildcard examples
The h_nt pattern matches hunt, hint, etc. The __pple pattern matches topple, supple, tipple,
etc.
Note that SQLite LIKE operator is case-insensitive. It means "A" LIKE "a" is true.

SELECT
name,
albumid,
composer
FROM
tracks
WHERE
composer LIKE '%Smith%'
ORDER BY
albumid;

Task: Create a query


To find tracks whose name starts with wild,
To find the tracks whose names ends with wild
To find the tracks whose names contain the Wild literal string
In
The SQLite IN operator determines whether a value matches any value in a list or a subquery.
The syntax of the IN operator is as follows:
SELECT
name,
albumid,
mediatypeid
FROM
tracks
WHERE
mediatypeid IN (2, 3);

Task: Create a query to show list of tracks whose genre id is not in a list of (1,2,3)

Between:

The BETWEEN operator is a logical operator that tests whether a value is in range of values. If th
e value is in the specified range, the BETWEEN operator returns true. The BETWEEN operator c
an be used in the WHERE clause of the SELECT, DELETE, UPDATE, and REPLACE statements.

SELECT
InvoiceId,
BillingAddress,
Total
FROM
invoices
WHERE
Total BETWEEN 14.91 and 18.86
ORDER BY
Total;
Task:
To find the invoices whose total are not between 1 and 20, you use the NOT BETWEEN operator
To find invoices whose invoice dates are from January 1 2010 and January 31 2010.
Limit
The LIMIT clause is an optional part of the SELECT statement. You use the LIMIT clause to
constrain the number of rows returned by the query.
SELECT
column_list
FROM
table
LIMIT row_count;

SELECT
trackId,
name
FROM
tracks
LIMIT 10;
SELECT
trackId,
name
FROM
tracks
LIMIT 10 OFFSET 10;

Task: To get the 5 shortest tracks, you sort the tracks by length specified by milliseconds column
using ORDER BY clause and get the first 5 rows using LIMIT clause.

ISNULL:

NULL is special. It indicates that a piece of information is unknown or not applicable.


For example, some songs may not have the songwriter information because we don’t know who
wrote them.

To store these unknown songwriters along with the songs in a database table, we must use NULL.

SELECT
Name,
Composer
FROM
tracks
WHERE
Composer IS NULL
ORDER BY
Name;
ISNOTNULL:

The IS NOT NULL operator returns 1 if the expression or column is not NULL, and 0 if the
expression or column is NULL.
Task: Finds tracks whose composers are not NULL

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy