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;