Categories: All - functions

by Marina Garayoa Moreno 24 days ago

35

summary_outline_marinagarayoa

MySQL's SELECT statement is used to retrieve data from a database, allowing you to specify which columns to return from a given table. For example, to get customer names and cities from a Customers table, you would use the SELECT CustomerName, City FROM Customers statement.

summary_outline_marinagarayoa

MySQL

SQL Values

DELETE

The SQL DELETE Statement

The DELETE statement is used to delete existing records in a table.

DELETE Syntax

DELETE FROM table_name WHERE condition;


Example:

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

UPDATE

The SQL UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.


UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;


Example:

UPDATE Customers

SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'

WHERE CustomerID = 1;

INSERT INTO

The SQL INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a table.

INSERT INTO table_name (column1, column2, column3, ...)

VALUES (value1, value2, value3, ...);


Example:

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)

VALUES ('Cardinal''Tom B. Erichsen''Skagen 21''Stavanger''4006''Norway');


Insert Multiple Rows

It is also possible to insert multiple rows in one statement.

To insert multiple rows of data, we use the same INSERT INTO statement, but with multiple values:


Example:

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)

VALUES

('Cardinal''Tom B. Erichsen''Skagen 21''Stavanger''4006''Norway'),

('Greasy Burger''Per Olsen''Gateveien 15''Sandnes''4306''Norway'),

('Tasty Tee''Finn Egan''Streetroad 19B''Liverpool''L1 0AA''UK');

SQL Queries

SELECT

The SQL SELECT Statement

The SELECT statement is used to select data from a database.

SELECT column1, column2, ...

FROM table_name;


Example:

Return data from the Customers table:

SELECT CustomerName, City FROM Customers;


HAVING

The SQL HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.


HAVING Syntax

SELECT column_name(s)

FROM table_name

WHERE condition

GROUP BY column_name(s)

HAVING condition

ORDER BY column_name(s);


Example:

SELECT COUNT(CustomerID), Country

FROM Customers

GROUP BY Country

HAVING COUNT(CustomerID) > 5;

GROUP BY

The SQL GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".


The GROUP BY statement is often used with aggregate functions (COUNT()MAX()MIN()SUM()AVG()) to group the result-set by one or more columns.


GROUP BY Syntax

SELECT column_name(s)

FROM table_name

WHERE condition

GROUP BY column_name(s)

ORDER BY column_name(s);


Example:

SELECT COUNT(CustomerID), Country

FROM Customers

GROUP BY Country;

FUNCTIONS

SQL Aggregate Functions

An aggregate function is a function that performs a calculation on a set of values, and returns a single value.

Aggregate functions are often used with the GROUP BY clause of the SELECT statement.


The GROUP BY clause splits the result-set into groups of values and the aggregate function can be used to return a single value for each group.

The most commonly used SQL aggregate functions are:



AVG

The SQL AVG() Function

The AVG() function returns the average value of a numeric column.


Syntax

SELECT AVG(column_name)

FROM table_name

WHERE condition;


Example:

Find the average price of all products:

SELECT AVG(Price)

FROM Products;

SUM

The SQL SUM() Function

The SUM() function returns the total sum of a numeric column.


Syntax

SELECT SUM(column_name)

FROM table_name

WHERE condition;


Example:

Return the sum of all Quantity fields in the OrderDetails table:

SELECT SUM(Quantity)

FROM OrderDetails;

COUNT

The SQL COUNT() Function

The COUNT() function returns the number of rows that matches a specified criterion.


Syntax

SELECT COUNT(column_name)

FROM table_name

WHERE con



Example:

Find the total number of rows in the Products table:

SELECT COUNT(*)

FROM Products;dition;

MIN AND MAX

The SQL MIN() and MAX() Functions

The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.


Syntax

SELECT MIN(column_name)

FROM table_name

WHERE condition;


SELECT MAX(column_name)

FROM table_name

WHERE condition;


MIN Example:

Find the lowest price in the Price column:

SELECT MIN(Price)

FROM Products;


MAX Example:

Find the highest price in the Price column:

SELECT MAX(Price)

FROM Products;

ANY AND ALL

The SQL ANY and ALL Operators

The ANY and ALL operators allow you to perform a comparison between a single column value and a range of other values.


The SQL ANY Operator

The ANY operator:

ANY means that the condition will be true if the operation is true for any of the values in the range.


ANY Syntax

SELECT column_name(s)

FROM table_name

WHERE column_name operator ANY

 (SELECT column_name

  FROM table_name

  WHERE condition);


ALL Syntax With SELECT

SELECT ALL column_name(s)

FROM table_name

WHERE condition;


Example ANY:

SELECT ProductName

FROM Products

WHERE ProductID = ANY

 (SELECT ProductID

  FROM OrderDetails

  WHERE Quantity = 10);


Example ALL:

SELECT ALL ProductName

FROM Products

WHERE TRUE;

TOP

The SQL SELECT TOP Clause

The SELECT TOP clause is used to specify the number of records to return.

The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.


Example:

Select only the first 3 records of the Customers table:

SELECT TOP 3 * FROM Customers;

AS

SQL Aliases

SQL aliases are used to give a table, or a column in a table, a temporary name.

Aliases are often used to make column names more readable.

An alias only exists for the duration of that query.

An alias is created with the AS keyword.


Syntax

When alias is used on column:

SELECT column_name AS alias_name

FROM table_name;


When alias is used on table:

SELECT column_name(s)

FROM table_name AS alias_name;



Example:

SELECT CustomerID AS ID

FROM Customers;

ORDER BY

The SQL ORDER BY

The ORDER BY keyword is used to sort the result-set in ascending(ASC) or descending(DESC) order.

SELECT column1, column2, ...

FROM table_name

ORDER BY column1, column2, ... ASC|DESC;


Example:

Sort the products by price:

SELECT * FROM Products

ORDER BY Price;

WHERE

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.

SELECT column1, column2, ...

FROM table_name

WHERE condition;


Example:

Select all customers from Mexico:

SELECT * FROM Customers

WHERE Country='Mexico';


Operators:

The following operators can be used in the WHERE clause:

=: Equal

>: Greater than

<: Less than

>=: Greater than or equal

<=: Less than or equal

<>: Not equal.

BETWEEN: Between a certain range

LIKE: Search for a pattern

IN: To specify multiple possible values for a column


Example:

Select all customers with a CustomerID greater than 80:

SELECT * FROM Customers

WHERE CustomerID 80;

EXIST

The SQL EXISTS Operator

The EXISTS operator is used to test for the existence of any record in a subquery.

The EXISTS operator returns TRUE if the subquery returns one or more records.


EXISTS Syntax

SELECT column_name(s)

FROM table_name

WHERE EXISTS

(SELECT column_name FROM table_name WHERE condition);


Example:

SELECT SupplierName

FROM Suppliers

WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);

BETWEEN

The SQL BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.

The BETWEEN operator is inclusive: begin and end values are included. 

Syntax

SELECT column_name(s)

FROM table_name

WHERE col

umn_name BETWEEN value1 AND value2;


Example:

Selects all products with a price between 10 and 20:

SELECT * FROM Products

IN

The SQL IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.


Syntax

SELECT column_name(s)

FROM table_name

WH



Example:

Return all customers from 'Germany', 'France', or 'UK'

SELECT * FROM Customers

WHERE Country IN ('Germany''France''UK');ERE column_name IN (value1, value2, ...);

NULL

NULL Values

It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

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;


IS NOT NULL Syntax

SELECT column_names

FROM table_name

WHERE column_name IS NOT NULL;

NOT

The NOT Operator

The NOT operator is used in combination with other operators to give the opposite result, also called the negative result.

In the select statement below we want to return all customers that are NOT from Spain:

SELECT column1, column2, ...

FROM table_name

WHERE NOT condition;


Example:

Select only the customers that are NOT from Spain:

SELECT * FROM Customers

WHERE NOT Country = 'Spain';

OR

The SQL OR Operator

The WHERE clause can contain one or more OR operators.

The OR operator is used to filter records based on more than one condition, like if you want to return all customers from Germany but also those from Spain:

SELECT column1, column2, ...

FROM table_name

WHERE condition1 OR condition2 OR condition3 ...;



Example:

Select all customers from Germany or Spain:

SELECT *

FROM Customers

WHERE Country = 'Germany' OR Country = 'Spain';

LIKE

The SQL LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.


There are two wildcards often used in conjunction with the LIKE operator:


LIKE Syntax

SELECT column1, column2, ...

FROM table_name

WHERE columnN LIKE pattern;


Example:

Select all customers that starts with the letter "a":

SELECT * FROM Customers

WHERE CustomerName LIKE 'a%';

ESCAPE

ESCAPE clause in LIKE operator

The ESCAPE clause is supported in the LIKE operator to indicate the escape character.

ESCAPE characters are used in the pattern string to indicate that any wildcard character that occurs after the escape character in the pattern string should be treated as a regular character.


The default escape character is backslash (\)


Syntax

LIKE 'pattern string' ESCAPE 'c'


Example

SELECT * FROM emp WHERE ENAME LIKE 'J%$_%' ESCAPE '$';

This matches all records with names that start with letter ’J’ and have the ’_’ character in them.

SELECT * FROM emp WHERE ENAME LIKE 'JOE$_JOHN' ESCAPE '$';

This matches only records with name ’JOE_JOHN’.

WILDCARDS

SQL Wildcard Characters

A wildcard character is used to substitute one or more characters in a string.


Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.


Wildcard Characters

%: Represents zero or more characters

_: Represents a single character

[]: Represents any single character within the brackets*

-:Represents any single character within the specified range


Example:

Return all customers that starts with the letter 'a':

SELECT * FROM Customers

WHERE CustomerName LIKE 'a%';

AND

The SQL AND Operator

The WHERE clause can contain one or many AND operators.

The AND operator is used to filter records based on more than one condition, like if you want to return all customers from Spain that starts with the letter 'G':

SELECT column1, column2, ...

FROM table_name

WHERE condition1 AND condition2 AND condition3 ...;


Example

Select all customers from Spain that starts with the letter 'G':

SELECT *

FROM Customers

WHERE Country = 'Spain' AND CustomerName LIKE 'G%';

DISTINCT

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values.

SELECT DISTINCT column1, column2, ...

FROM table_name;


Example:

Select all the different countries from the "Customers" table:

SELECT DISTINCT Country FROM Customers;



SQL Database

DROP DATABASE

The SQL DROP DATABASE Statement

The DROP DATABASE statement is used to drop an existing SQL database.

DROP DATABASE databasename;


Example:

DROP DATABASE marinaDB;

CREATE DATABASE

The SQL CREATE DATABASE Statement

The CREATE DATABASE statement is used to create a new SQL database.

CREATE DATABASE databasename;


Example:

CREATE DATABASE marinaDB;

DROP TABLE

The SQL DROP TABLE Statement

The DROP TABLE statement is used to drop an existing table in a database.

DROP TABLE table_name;


Example:

DROP TABLE Marina;

CREATE TABLE

The SQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a database.

CREATE TABLE table_name (

   column1 datatype,

   column2 datatype,

   column3 datatype,

  ....

);


Example:

CREATE TABLE Marina(

   MarinaID int,

   LastName varchar(255),

   FirstName varchar(255),

   Address varchar(255),

   City varchar(255)

);

ALTER TABLE

SQL ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

The ALTER TABLE statement is also used to add and drop various constraints on an existing table.

ALTER TABLE table_name

ADD column_name datatype;


Example:

ALTER TABLE Customers

ADD Email varchar(255);

CONSTRAINTS

SQL Create Constraints

Constraints can be specified when the table is created with the CREATE TABLE statement, or after the table is created with the ALTER TABLE statement.


CREATE TABLE Marina (

   column1 datatype constraint,

   column2 datatype constraint,

   column3 datatype constraint,

   ....

);


The following constraints are commonly used in SQL:



DEFAULT

SQL DEFAULT on CREATE TABLE

The following SQL sets a DEFAULT value for the "City" column when the "Marina" table is created:


Example:

CREATE TABLE Marina(

   ID int NOT NULL,

   LastName varchar(255NOT NULL,

   FirstName varchar(255),

   Age int,

   City varchar(255DEFAULT 'Sandnes'

);

CHECK

SQL CHECK on CREATE TABLE

The following SQL creates a CHECK constraint on the "Age" column when the "Marina" table is created. The CHECK constraint ensures that the age of a person must be 18, or older:


Example:

CREATE TABLE Marina(

   ID int NOT NULL,

   LastName varchar(255NOT NULL,

   FirstName varchar(255),

   Age int,

    CHECK (Age>=18)

);

FOREING KEY

SQL FOREIGN KEY on CREATE TABLE

The following SQL creates a FOREIGN KEY on the "MarinaID" column when the "Orders" table is created:


Example:

CREATE TABLE MarinaT(

   MarinaID int NOT NULL,

   LastName varchar(255NOT NULL,

   FirstName varchar(255),

   Age int,

    PRIMARY KEY (ID)

);


CREATE TABLE Orders (

   OrderID int NOT NULL,

   OrderNumber int NOT NULL,

   PersonID int,

    PRIMARY KEY (OrderID),

    FOREIGN KEY (MarinaID) REFERENCES MarinaT(MarinaID)

);


PRIMARY KEY

SQL PRIMARY KEY on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "ID" column when the "Marina" table is created:


Example:

CREATE TABLE Marina(

   ID int NOT NULL,

   LastName varchar(255NOT NULL,

   FirstName varchar(255),

   Age int,

    PRIMARY KEY (ID)

);

UNIQUE

SQL UNIQUE Constraint on CREATE TABLE

The following SQL creates a UNIQUE constraint on the "ID" column when the "Marina" table is created:


Example:

CREATE TABLE Marina(

   ID int NOT NULL UNIQUE,

   LastName varchar(255NOT NULL,

   FirstName varchar(255),

   Age int

);

NOT NULL

SQL NOT NULL on CREATE TABLE

The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept NULL values when the "Marina" table is created:


Example:

CREATE TABLE Marina(

   ID int NOT NULL,

    LastName varchar(255NOT NULL,

   FirstName varchar(255NOT NULL,

   Age int

);