Skip to content
Fix Code Error

How do I perform an IF…THEN in an SQL SELECT?

March 13, 2021 by Code Error
Posted By: Eric Labashosky

How do I perform an IF...THEN in an SQL SELECT statement?

For example:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product

Solution

The CASE statement is the closest to IF in SQL and is supported on all versions of SQL Server.

SELECT CAST(
             CASE
                  WHEN Obsolete = 'N' or InStock = 'Y'
                     THEN 1
                  ELSE 0
             END AS bit) as Saleable, *
FROM Product

You only need to do the CAST if you want the result as a Boolean value. If you are happy with an int, this works:

SELECT CASE
            WHEN Obsolete = 'N' or InStock = 'Y'
               THEN 1
               ELSE 0
       END as Saleable, *
FROM Product

CASE statements can be embedded in other CASE statements and even included in aggregates.

SQL Server Denali (SQL Server 2012) adds the IIF statement which is also available in access (pointed out by Martin Smith):

SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product
Answered By: Darrel Miller

Related Articles

  • When I use '/js/app.js' on my Laravel view my…
  • Replace every other instance of a string
  • Rails wrong number of arguments error when…
  • Callback functions in C++
  • Form field border-radius is not working only on the…
  • Maximum XOR With an Element From Array | Leetcode
  • 'block in draw' rails 6 routes
  • Use Set() in MobX with TypeScript?
  • Why is 2 * (i * i) faster than 2 * i * i in Java?
  • How do you sort table columns with Vue.js?
  • Adding gif image in an ImageView in android
  • Fastest way to iterate over all the chars in a String
  • Simple way to transpose columns and rows in SQL?
  • problem with client server unix domain stream…
  • How to filter a RecyclerView with a SearchView
  • Event Snippet for Google only shows one event while…
  • How can I find the product GUID of an installed MSI setup?
  • When is assembly faster than C?
  • Knight's tour Problem - storing the valid moves then…
  • Postman gives 401 Unauthorized - Spring Boot & MYSQL
  • Draw in Canvas by finger, Android
  • Javax.net.ssl.SSLHandshakeException:…
  • python How to get value(amount and number) from text file
  • ValueError Cannot assign "
  • How to keep disappearing Flutter Bottom Navigation…
  • Not submit any value if checkbox is empty
  • Replacing many missing columns in a Data Frame using…
  • What's the best way to get the last element of an…
  • Get selected item and its count
  • What does "Fatal error: Unexpectedly found nil while…
  • Elasticsearch does not return jsonp
  • Auto-fit TextView for Android
  • How to convert an object to JSON correctly in…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Django: Get first row from related table and show…
  • How to format a phone number in a textfield
  • Converting Oracle SQL Procedure into MySQL Stored Procedure
  • Efficient Algorithm for Bit Reversal (from…
  • Multiple separate IF conditions in SQL Server
  • Undefined reference to 'vtable for ✘✘✘'
  • T-SQL How to create tables dynamically in stored procedures?
  • Calculate time difference in minutes in SQL Server
  • Smart way to truncate long strings
  • Homebrew install specific version of formula?
  • Conversion failed when converting the varchar value…
  • Java Array, Finding Duplicates
  • Sending data in Laravel using Axios & Vue
  • "The system cannot find the file specified"
  • How to declare interfaces which are used by multiple…
  • I have tried to implement mergesort and am unable to…
  • How to register a custom callback after Ember.RSVP.hash
  • What is a NullReferenceException, and how do I fix it?
  • coalesce in javascript
  • C++ OpenGL stb_image.h errors
  • What am I doing wrong in my C binary search code?…
  • How do I install Java on Mac OSX allowing version switching?
  • How to compare Boolean?
  • Get next available date for an out-of-stock, but…
  • Get the contents of a table row with a button click
  • In Vue.js app; how to add 'active' class to button…
  • What is an IndexOutOfRangeException /…
  • How to use Servlets and Ajax?
  • Foreach in a Foreach in MVC View
  • v-data-table: bind a custom property to "items" slot
  • vue.js with Laravel pagination and filtering for list
  • List of ANSI color escape sequences
  • Vue price range filter
  • Generate SQL Create Scripts for existing tables with Query
  • #define macro for debug printing in C?
  • How to reset a prop value to it's original value in Vuejs
  • ValueError: invalid literal for int () with base 10
  • How to set HTML5 required attribute in Javascript?
  • Accessing a Shared File (UNC) From a Remote,…
  • SQL query return data from multiple tables
  • long long int vs. long int vs. int64_t in C++
  • Vue.js Router change url but not view
  • Java - get pixel array from image
  • C Argument number to create PGM images
  • Issues trying to install sylius/product-bundle to my…
  • Product Filter using Vue.js
  • Copy a file in a sane, safe and efficient way
  • [Vue warn]: Missing required prop: "productInfo"
  • Why does C++ code for testing the Collatz conjecture…
  • Is it possible to print a variable's type in standard C++?
  • How to sort the keySet() of a TreeMap with keys…
  • How do I return the response from an asynchronous call?
  • Getting [object Object] instead of object in React
  • How do I obtain a Query Execution Plan in SQL Server?
  • Implementation of user defined array on stack and/or…
  • Replace/Update The Existing Array of Object that…
  • Baffling variadic templates exercise
  • doGet and doPost in Servlets
  • Cannot get hash map value as ArrayList
  • What are the currently supported CSS selectors…
  • Cast from VARCHAR to INT - MySQL
  • When I delete multiple product in my basket only…
  • What is an optional value in Swift?
  • Fastest way to list all primes below N
  • Detect whether Office is 32bit or 64bit via the registry
  • How to properly do JSON API GET requests and assign…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can you find out which process is listening on a TCP or UDP port on Windows?

Next Post:

How to append something to an array?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error