Day16: SQL: What Can SQL Do?
Day16: SQL: What Can SQL Do?
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International
Organization for Standardization (ISO) in 1987
RDBMS
RDBMS stands for Relational Database Management System.
Day16: SQL 1
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL,
and Microsoft Access.
The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists
of columns and rows.
Example
SELECT * FROM Customers;
Every table is broken up into smaller entities called fields. The fields in the Customers table consist of CustomerID,
CustomerName, ContactName, Address, City, PostalCode and Country. A field is a column in a table that is designed to
maintain specific information about every record in the table.
A record, also called a row, is each individual entry that exists in a table. For example, there are 91 records in the above
Customers table. A record is a horizontal entity in a table.
A column is a vertical entity in a table that contains all information associated with a specific field in a table.
Syntax
CREATE DATABASE databasename;
Example
CREATE DATABASE testDB;
Day16: SQL 2
Syntax
CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, ....);
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
2. If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query.
However, make sure the order of the values is in the same order as the columns in the table. Here, the INSERT INTO syntax
would be as follows:
INSERT INTO table_name VALUES ( value1 , value2 , value3 , ...);
SELECT Syntax
SELECT column1 , column2, ... FROM table_name ;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select all the fields
available in the table, use the following syntax:
SELECT * FROM table_name;
Any text between -- and the end of the line will be ignored (will not be executed).
The following example uses a single-line comment as an explanation:
Day16: SQL 3
Example
-Select all:
The following example uses a single-line comment to ignore the end of a line:
Example
SELECT * FROM Customers -- WHERE City='Berlin';
Multi-line Comments
Multi-line comments start with /* and end with */ .
Example
/*Select all the columnsof all the recordsin the Customers table:*/ SELECT * FROM Customers;
Example
SELECT DISTINCT Country FROM Customers;
The following SQL statement lists the number of different (distinct) customer countries:
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
Day16: SQL 4
The SQL WHERE Clause
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
WHERE Syntax
SELECT column1 , column2, ... FROM table_name WHERE condition ;
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND are TRUE.
AND Syntax
SELECT column1, column2, ...FROM table_name WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...FROM table_name WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...FROM table_name WHERE NOT condition;
AND Example
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is "Berlin":
Example
SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin';
OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München":
Day16: SQL 5
Example
SELECT * FROM Customers WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
Example
SELECT * FROM Customers WHERE Country='Germany' OR Country='Spain';
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
Example
SELECT * FROM Customers WHERE NOT Country='Germany';
Example
SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München');
The following SQL statement selects all fields from "Customers" where country is NOT "Germany" and NOT "USA":
Example
SELECT * FROM Customers WHERE NOT Country='Germany' AND NOT Country='USA';
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use
the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...FROM table_nameORDER BY column1, column2, ... ASC|DESC;
Day16: SQL 6
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" column:
Example
SELECT * FROM CustomersORDER BY Country;
Example
SELECT * FROM CustomersORDER BY Country DESC;
Example
SELECT * FROM CustomersORDER BY Country, CustomerName;
Example
SELECT * FROM CustomersORDER BY Country ASC, CustomerName DESC;
Day16: SQL 7
GROUP BY Syntax
SELECT column_name(s)FROM table_nameWHERE conditionGROUP BY column_name(s)ORDER BY column_name(s);
Example
SELECT COUNT(CustomerID), CountryFROM CustomersGROUP BY Country;
Try it Yourself »
The following SQL statement lists the number of customers in each country, sorted high to low:
Example
SELECT COUNT(CustomerID), CountryFROM CustomersGROUP BY CountryORDER BY COUNT(CustomerID) DESC;
We will have to use the IS NULL and IS NOT NULL operators instead.
IS NULL Syntax
SELECT column_names FROM table_name WHERE column_name IS NULL;
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NULL;
Day16: SQL 8
Tip: Always use IS NULL to look for NULL values.
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT NULL;
UPDATE Syntax
UPDATE table_name SET column1 = value1, column2 = value2, ...WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause
specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and a new city.
Example
UPDATE CustomersSET ContactName = 'Alfred Schmidt', City= 'Frankfurt'WHERE CustomerID = 1;
The following SQL statement will update the ContactName to "Juan" for all records where country is "Mexico":
Example
UPDATE CustomersSET ContactName='Juan'WHERE Country='Mexico';
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
DELETE Syntax
Day16: SQL 9
DELETE FROM table_name WHERE condition;
MySQL Syntax:
SELECT column_name(s) FROM table_name WHERE condition LIMIT number ;
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)FROM table_nameWHERE condition;
MAX() Syntax
SELECT MAX(column_name)FROM table_nameWHERE condition;
The following SQL statement finds the price of the cheapest product:
Example
SELECT MIN(Price) AS SmallestPrice FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
Example
SELECT MAX(Price) AS LargestPrice FROM Products;
COUNT() Syntax
SELECT COUNT(column_name)FROM table_nameWHERE condition;
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT AVG(column_name) FROM table_name WHERE condition;
Day16: SQL 10
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT SUM(column_name) FROM table_name WHERE condition;
COUNT() Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID) FROM Products;
AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)FROM Products;
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
Example
SELECT SUM(Quantity)FROM OrderDetails;
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign and the underscore can also be used in combinations!
Day16: SQL 11
LIKE Syntax
SELECT column1, column2, ...FROM table_nameWHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" or "UK":
Example
SELECT * FROM CustomersWHERE Country IN ('Germany', 'France', 'UK');
BETWEEN Example
The following SQL statement selects all products with a price between 10 and 20:
Example
SELECT * FROM ProductsWHERE Price BETWEEN 10 AND 20;
Example
DROP TABLE Shippers;
Day16: SQL 12
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).
MySQL:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age
int, PRIMARY KEY (ID));
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent
table.
Look at the following two tables:
MySQL supports foreign keys, which permit cross-referencing related data across tables, and foreign key constraints,
which help keep the related data consistent.
A foreign key relationship involves a parent table that holds the initial column values, and a child table with column values
that reference the parent column values. A foreign key constraint is defined on the child table.
This following example relates parent and child tables through a single-column foreign key and shows how a foreign key
constraint enforces referential integrity.
Create the parent and child tables:
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id)
REFERENCES parent(id)
) ;
Day16: SQL 13
The insert operation is successful because parent_id 1 is present in the parent table.
Insert a row into the child table with a parent_id value that is not present in the parent table:
mysql> INSERT INTO child (id,parent_id) VALUES(2,2);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
(`test`.`child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`)
REFERENCES `parent` (`id`))
The operation fails because the specified parent_id value does not exist in the parent table.
Try to delete the previously inserted row from the parent table:
mysql> DELETE FROM parent WHERE id = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails
(`test`.`child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`)
REFERENCES `parent` (`id`))
This operation fails because the record in the child table contains the referenced id ( parent_id ) value.
When an operation affects a key value in the parent table that has matching rows in the child table, the result depends on
the referential action specified by ON UPDATE and ON DELETE subclauses of the FOREIGN KEY clause. Omitting ON
DELETE and ON UPDATE clauses (as in the current child table definition) is the same as specifying the RESTRICT option, which
rejects operations that affect a key value in the parent table that has matching rows in the parent table.
Day16: SQL 14
Data type Description
A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in
ENUM(val1, val2,
an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the
val3, ...)
order you enter them
SET(val1, val2, A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a
val3, ...) SET list
A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215.
Untitled MEDIUMINT(size)
The size parameter specifies the maximum display width (which is 255)
A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to
Untitled INT(size)
4294967295. The size parameter specifies the maximum display width (which is 255)
Untitled INTEGER(size) Equal to INT(size)
A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned
Untitled BIGINT(size) range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width
(which is 255)
A floating point number. The total number of digits is specified in size. The number of digits after the
Untitled FLOAT(size, d) decimal point is specified in the d parameter. This syntax is deprecated in MySQL 8.0.17, and it will be
removed in future MySQL versions
A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for
Untitled FLOAT(p) the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the
data type becomes DOUBLE()
A normal-size floating point number. The total number of digits is specified in size. The number of digits
Untitled DOUBLE(size, d)
after the decimal point is specified in the d parameter
DOUBLE
Untitled
PRECISION(size, d)
An exact fixed-point number. The total number of digits is specified in size. The number of digits after the
Untitled DECIMAL(size, d) decimal point is specified in the d parameter. The maximum number for size is 65. The maximum
number for d is 30. The default value for size is 10. The default value for d is 0.
Untitled DEC(size, d) Equal to DECIMAL(size,d)
Day16: SQL 15
Data type Description
DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31'
A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1000-01-01 00:00:00'
DATETIME(fsp) to '9999-12-31 23:59:59'. Adding DEFAULT and ON UPDATE in the column definition to get automatic initialization
and updating to the current date and time
A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00'
UTC). Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09
TIMESTAMP(fsp)
03:14:07' UTC. Automatic initialization and updating to the current date and time can be specified using DEFAULT
CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in the column definition
TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59'
A year in four-digit format. Values allowed in four-digit format: 1901 to 2155, and 0000.MySQL 8.0 does not support
YEAR
year in two-digit format.
SQL Keywords
Keyword Description
ADD Adds a column in an existing table
ADD CONSTRAINT Adds a constraint after a table is already created
ALL Returns true if all of the subquery values meet the condition
ALTER Adds, deletes, or modifies columns in a table, or changes the data type of a column in a table
ALTER COLUMN Changes the data type of a column in a table
ALTER TABLE Adds, deletes, or modifies columns in a table
AND Only includes rows where both conditions is true
ANY Returns true if any of the subquery values meet the condition
AS Renames a column or table with an alias
ASC Sorts the result set in ascending order
BACKUP DATABASE Creates a back up of an existing database
BETWEEN Selects values within a given range
CASE Creates different outputs based on conditions
CHECK A constraint that limits the value that can be placed in a column
COLUMN Changes the data type of a column or deletes a column in a table
CONSTRAINT Adds or deletes a constraint
CREATE Creates a database, index, view, table, or procedure
CREATE DATABASE Creates a new SQL database
CREATE INDEX Creates an index on a table (allows duplicate values)
CREATE OR REPLACE VIEW Updates a view
CREATE TABLE Creates a new table in the database
CREATE PROCEDURE Creates a stored procedure
CREATE UNIQUE INDEX Creates a unique index on a table (no duplicate values)
CREATE VIEW Creates a view based on the result set of a SELECT statement
DATABASE Creates or deletes an SQL database
DEFAULT A constraint that provides a default value for a column
Day16: SQL 16
Keyword Description
Day16: SQL 17
Keyword Description
SELECT TOP Specifies the number of records to return in the result set
SET Specifies which columns and values that should be updated in a table
TABLE Creates a table, or adds, deletes, or modifies columns in a table, or deletes a table or data inside a table
TOP Specifies the number of records to return in the result set
TRUNCATE TABLE Deletes the data inside a table, but not the table itself
UNION Combines the result set of two or more SELECT statements (only distinct values)
UNION ALL Combines the result set of two or more SELECT statements (allows duplicate values)
UNIQUE A constraint that ensures that all values in a column are unique
UPDATE Updates existing rows in a table
VALUES Specifies the values of an INSERT INTO statement
Day16: SQL 18