SQL SELECTION Flashcards
How to select all data from the table?
SELECT * FROM my_table_name;
How to select only rows which are equal by the condition?
# use = SELECT * FROM my_table_name WHERE city = 'Berlin';
How to select only rows which aren’t equal by the condition?
# use <> SELECT * FROM my_table_name WHERE city <> 'Berlin';
How to select only specific columns from the table? ( 2 ways)
define it explicitly instead of using *
SELECT city, country FROM customers; # another way SELECT customers.city, customers.country FROM customers;
How to select values by many conditions?
# use OR / AND SELECT * FROM Products WHERE price = 18 OR price = 19;
SELECT * FROM Products WHERE price = 18 AND name = ‘nik’;
Is it possible to return a result that is less or more than the given value?
Yes, use < or > or <=
SELECT * FROM Products WHERE price < 18
How to select only NULL/ not NULL values?
SELECT * FROM Products WHERE price IS NOT NULL;
SELECT * FROM Products WHERE price IS NULL;
How to select values by the last or first symbols?( 2 ways )
SELECT * FROM Customers WHERE city LIKE ‘B%n’
# => will return Berlin
SELECT * FROM Customers WHERE city LIKE ‘Be_n’
# => will return Bern
# ‘%’ - for many symbols, ‘_’ -> for only one symbol
How to select values from the specific range?
# use BETWEEN SELECT * FROM Products WHERE price BETWEEN 18 AND 22;
How to select values which are included in the array? Or not included?
use IN or NOT IN
SELECT * FROM Products WHERE name IN (‘nik’, ‘alex’)
SELECT * FROM Products WHERE name NOT IN (‘nic’,’alex’)
How to show a list of all databases?
SHOW DATABASES;
How to set the order of selection?
SELECT * FROM Products ORDER BY price;
How to set the order for several rows?
SELECT * FROM Products ORDER BY price, unit;
How to change order direction?
ASC - from low to up
# DESC - from up to low
SELECT * FROM Products ORDER BY price ASC;
SELECT * FROM Products ORDER BY price DESC;
How to get sum of the row?
SELECT SUM(price) FROM Products;
How to get sum fo the row by a group of values?
SELECT productName, SUM(price) FROM Products GROUP BY productName;
How to get average value of the row?
SELECT AVG(price) FROM Products;
How to get MIN/MAX value of the row?
SELECT MIN(price) FROM Products; SELECT MAX(price) FROM Products;
How to get a number of no empty row values from the table?
SELECT COUNT(price) FROM Products;
How to return only unique value?
SELECT DISTINCT productName FROM Products;
How to return limited number of values?
SELECT * FROM Products LIMIT 1;
# the following return 10 values starting from 0
SELECT * FROM Products LIMIT 0,10;
How to temporary change the name of the selected column/table? ( 2 ways )
SELECT name AS another_name FROM profession;
# another without AS
SELECT name another_name FROM profession;
How to select values with sub-request?
SELECT * FROM Products WHERE CategoryID IN (SELECT CategoryID FROM Categories);