SQL Query Examples
09.11.2017 11:47 226.220 Displayed

SQL Query Examples

Customer ID Name Surname Date of Birth City Gender Score
1 Ahmet Cansever 1956-02-19 00:00:00.000 Istanbul M 64
2 Mehmet Aydın 1976-02-19 00:00:00.000 Samsun M 55
3 Aliye Seven 1966-06-10 00:00:00.000 Konya F 45
4 Burak Sayın 1996-02-19 00:00:00.000 Istanbul M 23
5 Beyza Kılıç 1955-12-30 00:00:00.000 Manisa F 85

SQL SELECT

To list the name and surname columns in the customer table;

SELECT name, surname FROM customer;

To list all records in the customer table;

SELECT * FROM customer;

SQL SELECT DISTINCT

A column in a table may contain duplicate values. With DISTINCT, we can list only unique values.

SELECT DISTINCT city FROM customer;

SQL WHERE

With the WHERE keyword, we can list only the records that match the specified condition.

SELECT * FROM customer WHERE city='Istanbul';
SELECT * FROM customer WHERE gender='F';

Operators that can be used with WHERE

Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between
LIKE Pattern matching
IN Specify multiple values

SQL AND – OR Usage


SELECT * FROM customer
WHERE city='Istanbul'
AND gender='M';

SELECT * FROM customer
WHERE city='Istanbul'
OR city='Samsun';

SELECT * FROM customer
WHERE gender='F'
AND (city='Konya' OR city='Manisa');

SQL ORDER BY Usage

SELECT * FROM customer ORDER BY name;
SELECT * FROM customer ORDER BY name DESC;

INSERT INTO Usage


INSERT INTO customer(name, surname, birthDate, city, gender, score)
VALUES ('Ali','Şahin','2000-10-12','Burdur','M',68);

SQL UPDATE Usage


UPDATE customers
SET score=90
WHERE customerId=3;

SQL DELETE Usage


DELETE FROM customers
WHERE customerId=4;
DELETE FROM customers;

SQL SELECT TOP Usage

SELECT TOP 5 * FROM customers;

SQL LIKE Usage

SELECT * FROM customers WHERE city LIKE 'S%';
SELECT * FROM customers WHERE city LIKE '%s';
SELECT * FROM customers WHERE city LIKE '%tan%';

SQL IN Usage


SELECT * FROM customers
WHERE city IN ('Istanbul','Konya');

SQL BETWEEN Usage


SELECT * FROM customers
WHERE score NOT BETWEEN 70 AND 90;

SQL ALIASES Usage


SELECT name AS NAME, surname AS SURNAME, birthDate AS [DATE OF BIRTH]
FROM customers;

Group By and Having Usage

GROUP BY groups the selected dataset according to the specified columns. The HAVING clause is used after GROUP BY to filter grouped results.