Skip to content

Querying data

Table Structure

                                Table "public.product"
 Column  |     Type      | Collation | Nullable |               Default
---------+---------------+-----------+----------+-------------------------------------
 id      | integer       |           | not null | nextval('product_id_seq'::regclass)
 name    | character(50) |           | not null |
 price   | integer       |           | not null |
 country | character(25) |           | not null |
Indexes:
    "product_pkey" PRIMARY KEY, btree (id)

Selecting all columns

select * from product;
 id |                        name                        | price |          country
----+----------------------------------------------------+-------+---------------------------
  1 | Iphone                                             | 10000 | USA
  2 | Realme                                             |  1000 | INDIA
  3 | Vivo                                               |  2000 | CHINA
  4 | CG                                                 |   500 | NEPAL
  5 | Tesla                                              | 11500 | USA
  6 | Jio                                                |  1600 | INDIA
(6 rows)

Selecting specific columns

select id, name, price from product;
 id |                        name                        | price
----+----------------------------------------------------+-------
  1 | Iphone                                             | 10000
  2 | Realme                                             |  1000
  3 | Vivo                                               |  2000
  4 | CG                                                 |   500
  5 | Tesla                                              | 11500
  6 | Jio                                                |  1600
(6 rows)

Concatenating two columns

|| is concatenation operator

SELECT
   first_name || ' ' || last_name,
   email
FROM
   customer;

Column Aliases

Select name as product_name from product;
select name as "Product Name" from product;
SELECT
    first_name || ' ' || last_name AS full_name
FROM
    customer;

Selecting distinct column

select distinct country from product;
          country
---------------------------
 USA
 NEPAL
 CHINA
 INDIA
(4 rows)

Order By

SYNTAX: ORDER BY sort_expresssion [ASC | DESC] [NULLS FIRST | NULLS LAST]
Select * from product order by price;
Select * from product order by price ASC;
Select * from product order by price DESC;
select * from product order by price desc, name asc;
select
    name, length(name) as len
from
    product
order by
    len desc;
Select * from product order by price DESC nulls last;