Basic SQL
Basic SQL
2
1. SQL INTRODUCTION & DEFINITIONS
3
What you will learn about in this section
1. What is SQL?
5
SQL Introduction SQL stands for
Structured Query Language
11
Data Types in SQL SQLite uses:
integer, text
• Atomic types: and real
– Characters: CHAR(20), VARCHAR(50)
– Numbers: INT, BIGINT, SMALLINT, FLOAT
– Others: MONEY, DATETIME, …
relation
1. Which would you select as a key?
2. Is a key always guaranteed to exist?
i.e., if two tuples agree on the 3. Can we have more than one key?
values of the key, then they (key candidates and primary key)
must be the same tuple!
NULL and NOT NULL
• To say “don’t know the value” we use NULL
Students(sid:text, name:text, gpa: real)
19
2. SINGLE-TABLE QUERIES
20
What you will learn about in this section
25
A Few Details
• SQL commands are case insensitive:
– Same: SELECT, Select, select
– Same: Product, product
Versus Household
Category
Gadgets
SELECT Category
FROM Product Gadgets
Photography
Household 27
COUNT
COUNT is an aggregation function that returns the number of
elements.
28
ORDER BY: Sorting the Results
SELECT PName, Price, Manufacturer
FROM Product
WHERE Category=‘gizmo’ AND Price > 50
ORDER BY Price, PName
Note: LIMIT is not standard SQL (e.g., MS SQL Server uses SELECT TOP)
30
Operators
Some of the operators supported by SQL are:
=, == equal
!=, <> not equal
<, <= less than (or equal)
>, >= greater than (or equal)
+, -, /, * arithmetic operators
AND, OR, NOT logic operators
IS NULL, IS NOT NULL checks for NULL values
Example: Find products and their price + 8% sales tax for gadgets that cost at least $100
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2
32
LIKE: Simple String Pattern Matching
SELECT *
FROM Products
WHERE PName LIKE
‘%gizmo%’
33
Product
CASE Statement name category price
Example:
SELECT name,
CASE WHEN price > 200 THEN ‘Yes’ ELSE ‘No’ END AS expensive
FROM Product
34
Activities
• SQLite Operators
• Expressions
• Where clauses
• And & Or clauses
(http://www.tutorialspoint.com/sqlite/)
35