You are on page 1of 17

DATABASE PROGRAMMING

Dr.Amgad Monir
Contents

All commands in this slide


can be executed online through this link
SELECT
Here, the SQL command fetches age and country fields of all customers whose country is USA.

SELECT age, country FROM


Customers WHERE country = 'USA';
SELECT
Select all customers from the Customers table having last_name Doe and country USA

SELECT * FROM Customers


WHERE last_name = 'Doe' AND country = 'USA';
SELECT
Select first_name and last_name of all customers where the country is USA
or if their last name is Doe

SELECT first_name, last_name FROM Customers


WHERE country = 'USA' OR last_name = 'Doe';
Combining Multiple Operators
Select customers where the country is either USA or UK, and the age is less than 26.

SELECT * FROM Customers


WHERE (country = 'USA' OR country = 'UK') AND age < 26;
Combining Multiple Operators
Select all customers where the country is not USA and last_name is not Doe

SELECT * FROM Customers


WHERE country <> 'USA' AND last_name <> 'Doe';
SQL SELECT DISTINCT Statement
The SQL SELECT DISTINCT statement selects unique rows from a database table.

SELECT DISTINCT country FROM Customers;


SQL SELECT DISTINCT Statement
Select distinct rows in the combination of country and first_name.

SELECT DISTINCT country, first_name


FROM Customers;
DISTINCT with COUNT
IF we need to count the number of unique rows, we can use the
COUNT() function with DISTINCT.

SELECT COUNT(DISTINCT country)


FROM Customers;
SQL SELECT AS
The AS keyword is used to give columns or tables a temporary name that can be used
to identify that column or table later.

SELECT first_name AS name FROM


Customers;
SQL SELECT AS
Select customer_id as cid and first_name as name for all customers >= 28 years

SELECT customer_id AS cid, first_name AS name


FROM Customers
WHERE age>=28;
SQL AS With Expression
The SQL command selects first_name and last_name. And, the name of the column
will be full_name in the result set.

SELECT first_name || ' ' || last_name AS full_name


FROM Customers;
SQL LIMIT With OFFSET Clause
The OFFSET keyword is used to specify starting rows from where to select rows.

SELECT first_name, last_name FROM Customers


LIMIT 2 OFFSET 3;
SQL IN Operator With Columns
Select first_name, country if the USA value exists in the country field

SELECT first_name, country


FROM Customers
WHERE 'USA' in (country);
SQL NOT IN Operator
Select rows if UK or UAE is not in the country column.

SELECT first_name, country


FROM Customers
WHERE country NOT IN ('UK', 'UAE');
SQL IN Operator With Subquery

SELECT customer_id, first_name,last_name


FROM Customers
WHERE customer_id IN (
SELECT customer_id
FROM Orders
WHERE amount >=400
);

You might also like