Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways of returning hard coded values via SQL [duplicate]

I have some data that is hard coded in my select query.

The SQL is as follows:

SELECT 
'ZZ0027674',
'ZZ0027704',
'ZZ0027707',
'ZZ0027709',
'ZZ0027729',
'ZZ0027742',
'ZZ0027750'

Unfortunately it does not display the data. It just returns 7 columns and each column has each value. I just want 1 column with the different values.

Please provide me different solutions to display the data?

like image 293
PriceCheaperton Avatar asked Dec 24 '15 10:12

PriceCheaperton


People also ask

What is Hardcode in SQL?

Hardcoding is the practice of making code tailored to handle very specific cases. Here are some examples of hardcoding as applies to Drupal: Inserting an SQL query into a . tpl file. Writing a script that queries the database to make some changes to nodes.

How do you add duplicates in SQL?

To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.

Why am I getting duplicate records in SQL?

You are getting duplicates because more than one row matches your conditions. To prevent duplicates use the DISTINCT keyword: SELECT DISTINCT respid, cq4_1, dma etc...


2 Answers

You can use VALUES, aka Table Value Constructor, clause for hardcoded values:

SELECT *
FROM (VALUES('ZZ0027674'),('ZZ0027704'),('ZZ0027707'),
            ('ZZ0027709'),('ZZ0027729'),('ZZ0027742'),
             ('ZZ0027750')
     ) AS sub(c)

LiveDemo

Warning: This has limitation up to 1000 rows and applies to SQL Server 2008+. For lower version you could use UNION ALL instead.

EDIT:

Extra points if someone can show me unpivot ?

SELECT col
FROM (SELECT 'ZZ0027674','ZZ0027704','ZZ0027707',
             'ZZ0027709','ZZ0027729','ZZ0027742','ZZ0027750'
     ) AS sub(v1,v2,v3,v4,v5,v6,v7)
UNPIVOT
(
   col for c in (v1,v2,v3,v4,v5,v6,v7)
) AS unpv;

LiveDemo2

like image 190
Lukasz Szozda Avatar answered Sep 30 '22 15:09

Lukasz Szozda


Use union:

  SELECT 
'ZZ0027674' union all
SELECT 'ZZ0027704' union all
SELECT 'ZZ0027707' union all
SELECT 'ZZ0027709' union all
SELECT 'ZZ0027729' union all
SELECT 'ZZ0027742' union all
SELECT 'ZZ0027750'
like image 22
Mark PM Avatar answered Sep 30 '22 15:09

Mark PM