Select rows with even or odd values in SQL

 https://tableplus.com/blog/2019/09/select-rows-odd-even-value.html

Syntax

To find and return the records with the odd or even values, the most simple way is to check the remainder when we divide the column value by 2. When the remainder is 0, that’s an even number, otherwise, that’s an odd number.

Here is the syntax:

In PostgreSQL, My SQL, and Oracle, we use MOD function to check the remainder.

  • To find rows where a specified column has even values:
SELECT * 
FROM table_name 
WHERE mod(column_name,2) = 0;
  • To find rows where a specified column has odd values:
SELECT * 
FROM table_name 
WHERE mod(column_name,2) <> 0;

In MS SQL Server, there is no MOD function and you can use %.

  • To find rows where a specified column has even values:
SELECT *
FROM table_name 
where column_name % 2 = 0;
  • To find rows where a specified column has odd values:
SELECT *
FROM table_name 
where column_name % 2 <> 0;

Example

We have table dept_manager in MySQL:

emp_iddept_idfrom_dateto_date
110022d0011985-01-011991-10-01
110039d0011991-10-019999-01-01
110085d0021985-01-011989-12-17
110114d0021989-12-179999-01-01
110183d0031985-01-011992-03-21
110228d0031992-03-219999-01-01
110303d0041985-01-011988-09-09
110344d0041988-09-091992-08-02
110386d0041992-08-021996-08-30
110420d0041996-08-309999-01-01
110511d0051985-01-011992-04-25
110567d0051992-04-259999-01-01
110725d0061985-01-011989-05-06
110765d0061989-05-061991-09-12
110800d0061991-09-121994-06-28
110854d0061994-06-289999-01-01
111035d0071985-01-011991-03-07
111133d0071991-03-079999-01-01
111400d0081985-01-011991-04-08
111534d0081991-04-089999-01-01
111692d0091985-01-011988-10-17
111784d0091988-10-171992-09-08
111877d0091992-09-081996-01-03
111939d0091996-01-039999-01-01

Now find all the rows having emp_id as even number:

SELECT *
FROM dept_manager
WHERE MOD(emp_id, 2) = 0;

The results is:

emp_iddept_idfrom_dateto_date
110022d0011985-01-011991-10-01
110114d0021989-12-179999-01-01
110228d0031992-03-219999-01-01
110344d0041988-09-091992-08-02
110386d0041992-08-021996-08-30
110420d0041996-08-309999-01-01
110800d0061991-09-121994-06-28
110854d0061994-06-289999-01-01
111400d0081985-01-011991-04-08
111534d0081991-04-089999-01-01
111692d0091985-01-011988-10-17
111784d0091988-10-171992-09-08

Need a good GUI tool for databases? TablePlus provides a native client that allows you to access and

Không có nhận xét nào:

StaticImage

  import React , { useEffect , useRef } from "react" import { StaticImage } from "gatsby-plugin-image" impor...